How to set field values equal to null in RowUpdati

2019-08-29 23:43发布

This is my code:

    protected void ConfigurationGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        // row's Update button is clicked, but before the GridView control 
        // updates the row
        DropDownList ddlst = 
           ((DropDownList)ConfigurationGridView.Rows[e.RowIndex].FindControl("SubUnitDropDownList"));

        if (ddlst != null)
        {
            ListItem li = ddlst.SelectedItem;

            if (li != null)
            {
                if (Convert.ToInt32(li.Value) == -1)
                {
                    // next line is where the problem is
                    // null doesn't change the old value
                    // it does nothing, how to I change this value to null??
                    e.NewValues["SubUnitId"] = null;
                }
                else
                {
                    // we set the actual value
                    // this works nicely
                    e.NewValues["SubUnitId"] = li.Value;
                }
            }
        }
    }

Basically, I have one field that gets its value via a combo box, the first value in the combos represents the unassigned/not applicable/not set value, or the null value for that record, it works when I assign other values, say 1, 2, or 3, when the combo gets -1 I want to clear this value i.e. put the null value, but the line above doesn't seem to do anything, I've tried Nullable<int32>, Int32? value = null, Convert.ToInt32(null) actually puts 0 instead of null. When I try System.DBNull.Value I get an error: 'Object of type 'System.DBNull' cannot be converted to type 'System.Nullable`1[System.Int32]'.'.

What am I doing wrong? thanks in advance for your input.

3条回答
Bombasti
2楼-- · 2019-08-29 23:58

Maybe you can try this:

e.NewValues["SubUnitId"]=System.DBNull.Value
查看更多
放我归山
3楼-- · 2019-08-30 00:12

Try changing e.NewValues["SubUnitId"] = null;

To:

Nullable<Int32> notSetvalue = null;
e.NewValues["SubUnitId"] = notSetvalue;

If I am not mistaken, your field expects a nullable int32 type, but you are passing the DBNull object directly.

查看更多
再贱就再见
4楼-- · 2019-08-30 00:24

The solution turned out to be

e.NewValues["SubUnitId"] = "";

that works nicely.

查看更多
登录 后发表回答