I have a dropdownlist box
<asp:DropDownList ID="drpAvailableColours" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" EnableViewState="true" >
asp:DropDownList>
I am populating the database using the code---
DataSet dsColours = new DataSet();
string strColourQuery = "Select ProductName,ColourCode from ProductDet where ProductId in (select ProductId from ProductMaster where CatId = '1' and SubCatId='1' and BrandId='2' and SubBrandId='7')";
dsColours = db.GetTableDefinedDataSet(strColourQuery, "ProductColours");
if (dsColours.Tables["ProductColours"].Rows.Count > 0)
{
var query = dsColours.Tables["ProductColours"].AsEnumerable()
.GroupBy(x => x.Field<string>("ProductName").ToString())
.Select(x => x.First());
foreach (DataRow DistinctProducts in query)
{
drpAvailableColours.Items.Add(new ListItem(DistinctProducts["ProductName"].ToString(), DistinctProducts["ColourCode"].ToString()));
}
}
else
{
//postback
Label1.Text = drpAvailableColours.SelectedValue.ToString();
}
But I don't get the selected value from the dropdownlist in the label1
Also DropDownList1_SelectedIndexChanged doesn't trigger when I select from dropdownlist
Loading
Deepa SudhirPosted Mar 12, 2015, 9:14 AM
Deepa SudhirPosted Mar 12, 2015, 8:25 AM
Praveen SreeramPosted Mar 12, 2015, 5:32 AM
You didn't mention when you have written the above code. I assume you wrote that in Page_Load event.. Correct?
Just place the above code in If(!isPostBack) condition.
The reason you are not getting the Selected Value is, every time you change the value in the dropdown, the page will get posted to the server (AutoPostBack="True") and the Page_Load event will be fired (even before DropDownList1_SelectedIndexChanged) and the Dropdown will be bounded with new data and all the events will be attached again which causes the older events not getting fired.
So, if you wrote the above logic in Page_Load, the data to the dropdown will be bound only for the first and not the subsequent postbacks.
Hope my explanation is clear :-)
So, Use the following code.
Page_Load(args here)
{
If(!IsPostBack)
{
DataSet dsColours = new DataSet();
string strColourQuery = "Select ProductName,ColourCode from ProductDet where ProductId in (select ProductId from ProductMaster where CatId = '1' and SubCatId='1' and BrandId='2' and SubBrandId='7')";
dsColours = db.GetTableDefinedDataSet(strColourQuery, "ProductColours");
if (dsColours.Tables["ProductColours"].Rows.Count > 0)
{
var query = dsColours.Tables["ProductColours"].AsEnumerable()
.GroupBy(x => x.Field<string>("ProductName").ToString())
.Select(x => x.First());
foreach (DataRow DistinctProducts in query)
{
drpAvailableColours.Items.Add(new ListItem(DistinctProducts["ProductName"].ToString(), DistinctProducts["ColourCode"].ToString()));
}
}
}
DropDownList1_SelectedIndexChanged(args here)
{
Label1.Text = drpAvailableColours.SelectedValue.ToString();
}
Please let me know if you are still facing any problem?
Thanks,
Prawin