如何在GridView中进行行编辑时从数据库加载下拉列表值?

时间:2018-01-31 06:23:54

标签: c# asp.net gridview

我尝试了以下方式,数据集即将到来且表绑定。 但是,当行编辑事件

时,数据不会插入到gridview中指定的下拉列表中
  protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView2.EditIndex = e.NewEditIndex;
    int index = e.NewEditIndex;
  DropDownList ddl = (DropDownList)GridView2.Rows[index].FindControl("Receipttypeddl");
    if (ddl != null)
    {
        DataSet ds = new DataSet();
        SqlDataAdapter da;

        con.Open();
        string qry;
        qry = "select * from ReceiptType";
        SqlCommand cmd = new SqlCommand(qry);
        cmd.Connection = con;

        da = new SqlDataAdapter(cmd);

        da.Fill(ds);
        con.Close();
        ddl.DataSource = ds;
        ddl.DataTextField = "Receiptmode";
        ddl.DataValueField = "Receiptmode";
        ddl.DataBind(); 
        ListItem i = new ListItem("", "");//Data is not inserting into ddl
        ddl.Items.Insert(0, i);

    }

    DataTable dts = new DataTable();
    dts = (DataTable)ViewState["Receiptdetails"];
    GridView2.DataSource = dts;
    GridView2.DataBind();

}

1 个答案:

答案 0 :(得分:0)

你需要RowDataBound上的绑定下拉列表。

似乎没有必要为每个项目转到dB。

    protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView2.EditIndex = e.NewEditIndex;
        BindGridView();
    }

    private void BindGridView()
    {
        DataTable dts = new DataTable();
        dts = (DataTable)ViewState["Receiptdetails"];
        GridView2.DataSource = dts;
        GridView2.DataBind();
    }

    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddl = (DropDownList)e.Row.FindControl("Receipttypeddl");
            BindDropdown(ddl);
        }
    }

    DataTable ds = new DataTable();
    private void BindDropdown(DropDownList ddl)
    {
        if (ds.Rows.Count == 0)
        {
            SqlDataAdapter da;
            con.Open();
            string qry;
            qry = "select * from ReceiptType";
            SqlCommand cmd = new SqlCommand(qry);
            cmd.Connection = con;

            da = new SqlDataAdapter(cmd);

            da.Fill(ds);
            con.Close();
        }

        ddl.DataSource = ds;
        ddl.DataTextField = "Receiptmode";
        ddl.DataValueField = "Receiptmode";
        ddl.DataBind();
        ListItem i = new ListItem("", "");//Data is not inserting into ddl
        ddl.Items.Insert(0, i);
    }