开发者

Prevent Empty Gridview data from populating " " into textbox

开发者 https://www.devze.com 2023-01-16 09:51 出处:网络
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)

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)
    {

        txtCom开发者_运维技巧ment.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 = "";
}


I also had a problem like this one, and i found this useful too:

txtComment.Text = row.Cells[14].Text.Replace(" ", "");

i hope it can help you :)


Use NullDisplayText=" "

     <asp:BoundField DataField="EmployeeName" HeaderText="Name" NullDisplayText=" "/>


The issue is that you're accessing the Text property of the HTML cell rather than the data column. The gridview needs to display &nbsp; 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.


There is no need to write any code, just add HtmlEncode="false" to the Boundfield.


Use this:

Server.HtmlDecode()

For example:

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

It handles not only spaces, but also other conversions like ampersands(&) and etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号