如何从DropDownList中选择的值是里面的GridView [英] How to get selected value from DropDownList which is inside GridView
问题描述
我里面的GridView一个DropDownList。可以有的 N 的'行与具有不同值的一个DropDownList每一行的GridView号。我动态填充DropDownLists和所有的值在DropDownLists正确填充。
I have a DropDownList inside GridView. There can be 'n ' number of rows in a GridView with each row having a DropDownList with different values. I am populating DropDownLists dynamically and all the values are populated properly in DropDownLists.
当我改变的DropDownList的选定值的每一行和preSS按钮保存设置,我总是得到0指数,而不是我所选择的值的值。
When I change the selected value of DropDownList for each row and press the button to save these values, I always get the value of 0 index instead of the value that I have selected.
我发现了很多这样的问题,但没有人帮助我。什么是它不会从DropDownList的正确选择值的原因?任何想法?
I found lot of questions like this but none of them helps me. What's the reason it doesn't get the right selected value from DropDownList? Any ideas?
当我删除GridView的,只是使用的DropDownList然后正常工作。
When I remove the GridView and just use DropDownList then it works fine.
推荐答案
试试这个
<asp:TemplateField HeaderText="XYZ">
<ItemTemplate>
<asp:DropDownList runat="server" ID="MyDD" DataSourceId="MyDataSource" />
</ItemTemplate>
</asp:TemplateField>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string connectionString = WebConfigurationManager.ConnectionStrings[1].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
if (e.Row.RowType == DataControlRowType.DataRow)
{
con.Open();
var ddl = (DropDownList)e.Row.FindControl("ddlState");
int CountryId = Convert.ToInt32(e.Row.Cells[0].Text);
SqlCommand cmd = new SqlCommand("select * from State where CountryID = @CountryId", con);
cmd.Parameters.Add("@CountryID", CountryId);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddl.DataSource = ds;
ddl.DataTextField = "StateName";
ddl.DataValueField = "StateID";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("--Select--", "0"));
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddl= (DropDownList )GridView1.Rows[e.RowIndex].FindControl("ddlState");
string selectedvalue=ddl.selectedvalue;
//My custom code to change last moment values with that selected from DropDownList
e.NewValues.Add("State", selectedvalue);
}
这篇关于如何从DropDownList中选择的值是里面的GridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!