Joshua Slocum
Joshua Slocum

Reputation: 21

Blank Gridview Cell populates "&nbsp" into textbox

I've noticed that when i populate textboxes from a selected row in a gridview that if the field is blank it displays "&nbsp" in the textbox.

Here is the solution I came up with. I check each cell before adding it to the textbox.

I get the feeling that I'm either doing something wrong to have this problem in the first place or that there is a better way to handle this.

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{

    //// Get the currently selected row using the SelectedRow property.
    GridViewRow row = GridView1.SelectedRow;

    // Load data from selected row into textboxes
    if (row.Cells[1].Text.Trim() != " ")
    {
        txtEditCust_ID.Text = row.Cells[1].Text.Trim();
    }




}

Upvotes: 2

Views: 23965

Answers (7)

Ravi
Ravi

Reputation: 1

If you want to check the gridview cell value whether empty or null, use this:

string decodeCellValue = Context.Server.HtmlDecode(e.Row.Cells[i].Text).Trim();
if(string.IsNullOrEmpty(decodeCellValue))
{
  // Cell value empty or NULL
}
else
{
  // Have some value
}

Upvotes: 0

Nallware
Nallware

Reputation: 159

if (e.Row.RowType != DataControlRowType.Header && e.Row.RowType != DataControlRowType.Footer && e.Row.RowType != DataControlRowType.Pager) 

This removes the header, footer, and pager (if you are using) rows which took care of the   for me.

Upvotes: 0

yosh
yosh

Reputation: 3305

Still a minor hack, but probably better than dealing with &nbsp;. You can set NullDisplayText=" " on GridView column <asp:BoundField> and then use condition like for example:

if (String.IsNullOrWhiteSpace(e.Row.Cells[1].Text))
{
    // do something with e.Row
}

In this case, there is no &nbsp; to begin with.

Upvotes: 8

Pedro Muniz
Pedro Muniz

Reputation: 578

use

txtEditCust_ID.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());

Upvotes: 1

This works too. Add this piece of code under your rowDataBound event

if (e.Row.Cells[1].Text.Length == 0 || e.Row.Cells[1].Text.Equals("&nbsp;") || e.Row.Cells[1].Text.Equals("") || e.Row.Cells[1].Text.Equals(string.Empty))
                {
                    e.Row.Cells[1].Text = string.Empty;
                }

Upvotes: 1

gell
gell

Reputation: 51

row.Cells[1].Text.Trim()

is not working for &nbsp;, replace it instead:

row.Cells[1].Text.Replace("&nbsp;", "")

Upvotes: 5

Jamie
Jamie

Reputation: 988

Remove the if statement, just use:

txtEditCust_ID.Text = row.Cells[1].Text.Trim(); 

You are trimming it so it should remove the &nbsp; anyway.

Upvotes: 0

Related Questions