如何从Gridview文本框中找到空值[c#]

本文关键字:空值 Gridview 文本 | 更新日期: 2023-09-27 18:02:27

我试图禁用文本框,如果文本框值为空,但我不知道我在哪里做错了以下不工作,请检查并分享您的建议。

WebForm:

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            onrowdatabound="GridView1_RowDataBound">
            <Columns>
                <asp:TemplateField HeaderText="GROUP">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox2" commandargument="Now_cmd" runat="server" 
            value='<%# Eval("now") %>'></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="Textbox2"></cc1:CalendarExtender>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ACTIVITY">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox3" commandargument="after_cmd" value='<%# Eval("afteronehour") %>' runat="server" 
            ></asp:TextBox>
            <cc1:CalendarExtender ID="CalendarExtender2" runat="server" TargetControlID="Textbox3"></cc1:CalendarExtender>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
后台代码:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            string value = e.Row.Cells[i].Text.ToString();
            if (e.Row.Cells[i].Text.ToString() == string.Empty)
            {
                e.Row.Cells[i].Enabled = false;
            }
        }
    }
}
我输入:

2015-07-03 09:44:02.380     2015-07-04 09:44:02.380
2015-07-03 09:4`4:53.360    2015-07-04 09:44:53.360
2015-07-03 09:47:00.580     NULL
2015-07-03 09:47:00.580     2015-07-04 09:44:53.360

所以我需要禁用NULL值复选框

如何从Gridview文本框中找到空值[c#]

您将TextBoxDataSource列绑定,而不是单元格,因此您应该在文本框中寻找文本,而不是单元格。你也可以使用FindControl来代替循环GridView行。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{    
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
      TextBox tb1= (TextBox)e.Row.FindControl("TextBox2");
    if(String.IsNullOrEmpty(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "now"))))
         tb1.Enabled = false; 
      TextBox tb2= (TextBox)e.Row.FindControl("TextBox3");
      if(String.IsNullOrEmpty(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "afteronehour"))))
         tb2.Enabled = false; 
   }
}

您应该使用IsNullOrEmpty()方法检查nullempty字符串,该方法将检查字符串是否为nullempty

if (string.IsNullOrEmpty(e.Row.Cells[i].Text))
{
  e.Row.Cells[i].Enabled = false;
}
for (int r = 0; r < GridView1.Rows.Count; r++)
{
    TextBox tb1 = (TextBox)GridView1.Rows[r].FindControl("TextBox2");
    TextBox tb2 = (TextBox)GridView1.Rows[r].FindControl("TextBox3");
if(tb1.Text==null)
{
tb1.Enabled=false;
}
else
{
tb1.Enabled=true;
}
if(tb2.Text==null)
{
tb2.Enabled=false;
}
else
{
tb2.Enabled=true;
}
}