我动态添加值到处于GridView中柱之一DROPDOWNLIST。
问题是,在下拉列表中选择的值不会被保存或者在添加新行维持? 任何想法,我可能做错了。 这里是我的代码..
这里是我的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>
这里是结合一个按钮被点击时的数据,以动态的GridView的代码。
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();
}
}
}
}