如何访问列表项以更改它们的值

How do I access List items in order to change their values

我想使用与我的数据库不同的 table 动态填充带有文本和值的下拉列表。我正在使用此代码:

    protected void MachineGrid_RowEditing(object sender, GridViewEditEventArgs e)
    {
        int index = e.NewEditIndex;
        var ddl = MachineGrid.Rows[index].FindControl("OSDropDownList") as DropDownList;
    }

访问下拉列表。然后我尝试使用以下两个代码片段来修改其中一个列表项,但都给了我以下错误

"System.NullReferenceException: 'Object reference not set to an instance of an object."

代码 1:

        var li = ddl.SelectedItem;
        li.Text = "test";

代码 2:

        var li = ddl.Items[0];
        li.Text = "test";

谢谢!

使用会 通过查询填充数据表并为下拉列表提供数据源。

yourDropDownList.DataSource= dt;
yourDropDownList.DataTextField="StringColumnName";
yourDropDownList.DataValueField="integerColumnName";
yourDropDownList.DataBind();