简体   繁体   中英

Dropdownlist in Gridview value

I am dynamically adding values to the dropDownlist which is one of the column in Gridview.

The problem is the value selected in dropdown list is not saved or maintained when a new row is added ?. Any idea what I could be doing wrong. Here is the code which I have ..

Here is my Gridview

   <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" OnDataBound="GridView1_DataBound">
                    <AlternatingRowStyle BackColor="White" />
                    <Columns>
                        <asp:boundfield datafield="ID" headertext="categoryid" />
<asp:boundfield datafield="univirsity" headertext="category name" />

                        <asp:templatefield headertext="products">
<itemtemplate>
<asp:dropdownlist id="dropdownlist1" runat="server">
</asp:dropdownlist>
</itemtemplate>
</asp:templatefield>
                    </Columns>

                </asp:GridView>

Here is the code which binds the data to Gridview dynamically when a button is clicked.

if (!Page.IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("ID", System.Type.GetType("System.Int32"));
                dt.Columns.Add("univirsity", System.Type.GetType("System.Int32"));
                dt.Columns.Add("major", System.Type.GetType("System.Int32"));
                Session["MyDataTable"] = dt;
            }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            DataTable t = (DataTable)Session["MyDataTable"];
            DataRow row1 = t.NewRow();

            row1["ID"] = t.Rows.Count + 1;
            row1["univirsity"] = 3;
           // row1["major"] = 31;
            t.Rows.Add(row1);

            Session["MyDataTable"] = t;
            GridView1.DataSource = t;
            GridView1.DataBind(); 
        }

 protected void GridView1_DataBound(object sender, EventArgs e)
        {
            //addControl();

            ArrayList list = new ArrayList();
            list.Add("DMG");
            list.Add("SVC");

            foreach (GridViewRow row in GridView1.Rows)
            {
                // int key = (int)GridView1.DataKeys[row.RowIndex].Value;
                if (row.RowType == DataControlRowType.DataRow)
                {
                    DropDownList dl = (DropDownList)row.FindControl("dropdownlist1");

                    string sel = dl.SelectedValue;
                    if (!String.IsNullOrEmpty(sel))
                    {
                        dl.DataSource = list;
                        dl.DataBind();
                        dl.SelectedValue = sel;
                    }
                    else
                    {
                        dl.DataSource = list;
                        dl.DataBind();

                    }

                }
            }
        }

You're not doing anything 'wrong' as such, you're just expecting the wrong thing. Templated controls such as gridviews function this way; if you want the selected value of a control within your template to persist, you'll have to do it yourself.

I would advise not storing large amounts of data in Session but I'm going to assume you know that, and your scenario is not intended to scale to millions of users with several rows in that datatable.. each.

In your case, I would add another column to that datatable to store the 'product' value; sync it with each postback, and on re-binding make sure you set the dropdownlist value from the table value: -

protected override void OnLoad(EventArgs e)
{
    if (!Page.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ID", typeof(int));
        dt.Columns.Add("univirsity", typeof(int));
        dt.Columns.Add("major", typeof(int));
        // our new column
        dt.Columns.Add("selectedProduct", typeof(string));
        Session["MyDataTable"] = dt;
    }
    else
    {
        // on each postback, loop through the grid and update
        // the datatable

        // get our table AsEnumerable, so we can use LINQ expressions on it
        var table = ((DataTable)Session["MyDataTable"]).AsEnumerable();

        foreach (GridViewRow gridRow in GridView1.Rows)
        {
            // get this row's ID from the grid
            int id = Convert.ToInt32(gridRow.Cells[0].Text);

            // and get the matching datarow from the table
            var tableRow = table.Where(x => (int)x["ID"] == id)
                                .SingleOrDefault();

            if (tableRow != null)
            {
                var ddl = (DropDownList)gridRow.FindControl("dropdownlist1");
                tableRow["selectedProduct"] = ddl.SelectedValue;
            }
        }
    }

    base.OnLoad(e);
}

void button1_Click(object sender, EventArgs e)
{
    DataTable t = (DataTable)Session["MyDataTable"];
    DataRow   row1 = t.NewRow();

    row1["ID"] = t.Rows.Count + 1;
    row1["univirsity"] = 3;
    // set default value for new column
    row1["selectedProduct"] = "DMG";

    t.Rows.Add(row1);

    Session["MyDataTable"] = t;
    GridView1.DataSource = t;
    GridView1.DataBind();
}

protected void GridView1_DataBound(object sender, EventArgs e)
{
    ArrayList list = new ArrayList();
    list.Add("DMG");
    list.Add("SVC");

    // get our table again
    var table = ((DataTable)Session["MyDataTable"]).AsEnumerable();

    foreach (GridViewRow gridRow in GridView1.Rows)
    {
        if (gridRow.RowType == DataControlRowType.DataRow)
        {
            // get our id and tablerow again
            int id = Convert.ToInt32(gridRow.Cells[0].Text);
            var tableRow = table.Where(x => (int)x["ID"] == id)
                                .SingleOrDefault();

            // bind the list
            DropDownList dl = (DropDownList)gridRow.FindControl("dropdownlist1");
            dl.DataSource = list;
            dl.DataBind();

            // set value from tablerow.selectedProduct
            dl.SelectedValue = (string)tableRow["selectedProduct"];
        }
    }
}

当您在gridview中有新行时,是否尝试使用循环重新加载该下拉列表?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM