【问题标题】:Prevent Empty Gridview data from populating " " into textbox防止空的 Gridview 数据将“ ”填充到文本框中
【发布时间】:2010-09-17 18:16:00
【问题描述】:

我有这段代码,它根据网格视图的选定行中的单元格填充文本框

 protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

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

    }

如果 Cell[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 = "";
}

【问题讨论】:

  • 你试过row.Cells[14].Text = string.Empty;或= "";吗?
  • 我都试过了 =string.Empty;和="";我仍然得到 &nbsp

标签: c# asp.net gridview


【解决方案1】:

我也遇到过类似的问题,我发现这也很有用:

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

希望对你有帮助:)

【讨论】:

    【解决方案2】:

    使用 NullDisplayText=""

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

    【讨论】:

      【解决方案3】:

      问题在于您访问的是 HTML 单元格的 Text 属性,而不是数据列。 gridview 需要在一个空的表格单元格中显示&amp;nbsp;,以便该表格单元格在呈现给某些浏览器时仍然可见。这是因为 HTML,与您的数据或代码没有任何关系;

      你应该做的是这样的:

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

      根据 DataItem 的实际情况,访问数据项属性的格式会有所不同,您可以将其转换为适合您的数据源的对象类型,然后相应地访问其属性。

      编辑:我更改了示例代码以演示将 DataItem 属性转换为 DataRow 对象。您需要将其转换为您作为数据源提供的任何类型。我希望这更清楚。

      【讨论】:

      • 我在尝试时收到此错误消息“无法使用 [] 将索引应用于 'object' 类型的表达式”
      • @JoshuaSlocum:请参阅我上面的编辑,您需要将 DataItem 转换为用作数据源的任何类型的对象。
      【解决方案4】:

      使用这个:

      Server.HtmlDecode()
      

      例如:

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

      它不仅可以处理空格,还可以处理其他转换,例如 & 符号 (&) 等。

      【讨论】:

        【解决方案5】:

        无需编写任何代码,只需将 HtmlEncode="false" 添加到 Boundfield 即可。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-09-23
          • 1970-01-01
          • 2012-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多