views:

62

answers:

1

I have this code that populates a textbox based on a cell in the selected row of a gridview

 protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

        txtComment.Text = row.Cells[14].Text.Trim();

    }

It displays   in the txtComment textbox if Cell[14] has no data.

Is there a way to prevent the   from appearing when there is no data in the cell of the selected row?


Edit I tried this and it didn't work

if (row.Cells[14].Text.Trim().Length > 1)
{
    txtComment.Text = row.Cells[14].Text.Trim();
}
else
{
    txtComment.Text = row.Cells[14].Text = "";
}

===================================================================

This worked

if (row.Cells[14].Text.Trim()!=" ")
{
    txtComment.Text = row.Cells[14].Text.Trim();
}
else
{
    txtComment.Text = row.Cells[14].Text = "";
}
+1  A: 

The issue is that you're accessing the Text property of the HTML cell rather than the data column. The gridview needs to display   in an empty table cell in order for that table cell to still be visible when rendered to some browsers. This is because of HTML and doesn't have anything to do with your data or code;

What you should be doing is something like this:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    DataRow myRow = (DataRow)GridView1.SelectedRow.DataItem;
    txtComment.Text = myRow[14];
}

The format for accessing the data item property is going to be a little different based on what that DataItem actually is, you can cast it to the type of object that fits your data source and then access its properties accordingly.

EDIT: I changed the example code to demonstrate casting the DataItem property to a DataRow object. You need to cast it to whatever type you are feeding as a DataSource. I hope this is more clear.

Coding Gorilla
I'm getting this error message when I try it "Cannot apply indexing with [] to an expression of type 'object'"
Joshua Slocum
@JoshuaSlocum: See my edits above, you need to cast the DataItem to whatever type of object is being used as the data source.
Coding Gorilla