Set the current value of gridview DDL on EditItemTemplate

后端 未结 2 1173
刺人心
刺人心 2021-01-17 04:30

How do I set the selected value in a gridview dropdownlist to what is in the current record like I currently do for a text box.

I am hoping the user can look at the

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-17 04:33

    You will need to use the OnRowDataBound event for that.

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //check if the row is a datarow
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //check if the row is in edit mode
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                //find the dropdownlist in the row using findcontrol
                DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList");
    
                //fill the dropdownlist from code behind if needed
                ddl.DataSource = source;
                ddl.DataTextField = "key";
                ddl.DataValueField = "valee";
                ddl.DataBind();
    
                //cast the dataitem back to a datarowview
                DataRowView row = e.Row.DataItem as DataRowView;
    
                //set the correct listitem as selected
                ddl.SelectedValue = row["myValue"].ToString();
            }
        }
    }
    

提交回复
热议问题