C# 防止填充空的Gridview数据&;nbsp&引用;输入文本框
我有一段代码,它基于gridview选定行中的单元格填充文本框C# 防止填充空的Gridview数据&;nbsp&引用;输入文本框,c#,asp.net,gridview,C#,Asp.net,Gridview,我有一段代码,它基于gridview选定行中的单元格填充文本框 protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { txtComment.Text = row.Cells[14].Text.Trim(); } 如果单元格[14]没有数据,它会在txtComment文本框中显示 当所选行的单元格中没有数据时,是否有方法防止出现 编辑 我试过了,但没用 if
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
txtComment.Text = row.Cells[14].Text.Trim();
}
如果单元格[14]没有数据,它会在txtComment文本框中显示
当所选行的单元格中没有数据时,是否有方法防止出现
编辑 我试过了,但没用
if (row.Cells[14].Text.Trim().Length > 1)
{
txtComment.Text = row.Cells[14].Text.Trim();
}
else
{
txtComment.Text = row.Cells[14].Text = "";
}
===================================================================
这起作用了
if (row.Cells[14].Text.Trim()!=" ")
{
txtComment.Text = row.Cells[14].Text.Trim();
}
else
{
txtComment.Text = row.Cells[14].Text = "";
}
问题是您正在访问HTML单元格的文本属性,而不是数据列。gridview需要在空表单元格中显示
,以便在呈现给某些浏览器时该表单元格仍然可见。这是因为HTML,与您的数据或代码没有任何关系
你应该这样做:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRow myRow = (DataRow)GridView1.SelectedRow.DataItem;
txtComment.Text = myRow[14];
}
根据数据项的实际情况,访问数据项属性的格式将略有不同,您可以将其转换为适合数据源的对象类型,然后相应地访问其属性
编辑:我更改了示例代码以演示如何将DataItem属性强制转换为DataRow对象。您需要将其转换为作为数据源提供的任何类型。我希望这更清楚。我也遇到过类似的问题,我发现这也很有用:
txtComment.Text = row.Cells[14].Text.Replace(" ", "");
我希望它能帮助您:)无需编写任何代码,只需将HtmlEncode=“false”添加到Boundfield。使用NullDisplayText=“”
使用以下方法:
Server.HtmlDecode()
例如:
txtComment.Text = Server.HtmlDecode(row.Cells[14].Text);
它不仅处理空格,还处理其他转换,如符号(&)等。您是否尝试过
row.Cells[14].Text=string.Empty代码>或=“”代码>?我尝试了两个=string.Empty;及‘’;我仍然得到了 I,当我尝试“无法将[]索引应用于'object'类型的表达式”时,我收到了这个错误消息@JoshuaSlocum:请参见我上面的编辑,您需要将数据项强制转换为用作数据源的任何类型的对象。
txtComment.Text = Server.HtmlDecode(row.Cells[14].Text);