null引用with和if语句c#

时间:2012-10-18 16:44:21

标签: c# asp.net

我只想检查空文本框,如果在RowEditing事件中它们为null,则将文本更改为框。我只是想不出来。当然,当填充网格时,一些框将为空。另一个问题是我是否将其置于正确的事件中?

以下是行编辑事件:

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{        
    fill_grid();

    //Set the edit index.
    GridView1.EditIndex = e.NewEditIndex;
    //Bind data to the GridView control.
    check_grid_boxes();
    GridView1.DataBind();
}

这是check_grid_boxes方法:

protected void check_grid_boxes()
{
    if (gtxtLane.Text == "")
    {
        gtxtLane.Text = "0";
    }
    else if (gtxtCarriers.Text == "")
    {
        gtxtCarriers.Text = "0";
    }
    else if (gtxtREV.Text == "")
    { 
        gtxtREV.Text = "0";
    }
    return;
}

在提及Java Script或Jquery之前。这是一个Web控件,我尝试使用java无法正常工作。

我将代码更改为:

  protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            fill_grid();
            GridView1.EditIndex = e.NewEditIndex;

            var lane = (TextBox)GridView1.Rows[e.NewEditIndex].FindControl("gtxtLane");
            var car = (TextBox)GridView1.Rows[e.NewEditIndex].FindControl("gtxtCarriers");
            var badcar = (TextBox)GridView1.Rows[e.NewEditIndex].FindControl("gtxtBadCarriers");

            if (String.IsNullOrEmpty(lane.Text))
            {
                lane.Text = "0";
            }
            else if (String.IsNullOrEmpty(badcar.Text))
            {
                badcar.Text = "0";
            }
            else if (String.IsNullOrEmpty(car.Text))
            {
                car.Text = "0";
            }
               GridView1.DataBind();
         }

4 个答案:

答案 0 :(得分:1)

您必须获得对正在编辑的行内的TextBox的引用,如下所示:

GridView1.EditIndex = e.NewEditIndex;

TextBox gtxtLane = (TextBox)GridView1.Rows[e.NewEditIndex].FindControl("gtxtLane");

答案 1 :(得分:1)

DUH !!!!怎么回事 - >选择isnull(lane,'0')作为Lane< ---。我简直不敢相信我没想到!!浪费了6个小时!!

答案 2 :(得分:0)

您可以使用gridview的nulldisplaytext属性

<asp:boundfield datafield="discounttype"
            nulldisplaytext="0"
            headertext="Discount Type"/>

答案 3 :(得分:0)

我猜你得到了一个参考问题,因为编译器不知道从哪里得到gtxtLane,其余来自。{请记住,网格中的每一行都有自己的这些控件版本,因此您需要直接引用它们。您可以在行对象上使用FindControl。您可以从GridViewEditEventArgs获取行对象的引用。您的代码看起来像这样(e引用GridViewEditEventArgs

var gtxtLane = (TextBox)GridView1.Rows[e.NewEditIndex].FindControl("gtxtLane");
if (gtxtLane.Text == "")
{
    gtxtLane.Text = "0";
}

e.NewEditIndex获取正在编辑的行的索引,我们使用它来从gridview获取行对象,然后我们找到所需的控件,并将其转换为TextBox,然后使用它。冲洗并重复。