Set Dropdownlist value in listview on itemdatabound
-
23-09-2019 - |
Question
i have dropdownlist of year which is coming dynamically.i have filled the dropdownlist using object datasource.on inserting in the listview control it is working fine. but when i click on edit button that dropdownlist value should be set which is coming from the database. e.g. if i have a row which contains Year=2006 and month="Jan" then on click on edit button these dropdown list should be fill up.
i have written the code in ItemDataBound to set the value of the dropdownlilst.but when i use findcontrol its taking null so object reference error is coming. so please provide me the solution.
thanks
samir
Solution 2
i have written the below code
protected void ListView_Articles_ItemDataBound(object sender, ListViewItemEventArgs e ) {
if (e.Item.ItemType == ListViewItemType.DataItem)
{
if (cmd == "edit")
{
// Display the e-mail address in italics.
int month, year;
month = Convert.ToDateTime(DataBinder.Eval(((ListViewDataItem)e.Item).DataItem,"Created")).Month;
year = Convert.ToDateTime(DataBinder.Eval(((ListViewDataItem)e.Item).DataItem, "Created")).Year;
ListViewDataItem item = (ListViewDataItem)e.Item;
DropDownList ddlmonth = (DropDownList)e.Item.FindControl("ddlmonth");
DropDownList ddlyear = (DropDownList)e.Item.FindControl("ddlyear");
ListItem lstitem = ddlyear.Items.FindByValue(year.ToString());
// i found that ddlyear is null so it unable to bind the data.
if (ddlmonth != null)
{
foreach (ListItem monthitem in ddlmonth.Items)
{
if (int.Parse(monthitem.Value) == month)
{
ddlmonth.ClearSelection();
monthitem.Selected = true;
return;
}
}
}
if (ddlyear != null)
{
foreach (ListItem yearitem in ddlyear.Items)
{
if (int.Parse(yearitem.Value) == year)
{
ddlyear.ClearSelection();
yearitem.Selected = true;
return;
}
}
}
}
}
}
OTHER TIPS
protected void MyListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
DropDownList ddl = (DropDownList)e.Item.FindControl("nameOfDDLOnAspxPage");
ddl.SelectValue = (however you are getting the year data for this row);
}
}