I have seen multiple posts regarding this subject and the answer is pretty much the same. To set the selecteditem programmatically use the following code:
DropDownList1.DataBind(); // get the data into the list you can set it
DropDownList1.Items.FindByValue("SOMECREDITPROBLEMS").Selected = true;
My scenario is slightly different. I'm trying to set the value of a dropdownlist in a gridview.
I am able to populate the dropdownlist, but not able to set the selecteditem or selectedindex.
Gridview
<asp:GridView ID="gvSubject" runat="server"
CssClass="table table-striped clientTblEnabled"
OnRowDataBound="gvSubject_RowDataBound"
AutoGenerateColumns="false"
OnPreRender="gvSubject_PreRender"
GridLines="Both" PageSize="50">
<Columns>
<asp:TemplateField HeaderText="Subject Date">
<ItemTemplate>
<asp:Label ID="lblSubjectDate" runat="server" Text='<%# Bind("SubjectDateTime", "{0:MM/dd/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject">
<ItemTemplate>
<asp:Label ID="lblSubject" runat="server" Text='<%# Bind("SubjectDesc") %>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddlSubject" runat="server" CssClass="input-xlarge controls"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No Results found
</EmptyDataTemplate>
</asp:GridView>
Populate dropdownlist
protected void gvSubject_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlSubject = e.Row.FindControl("ddlSubject") as DropDownList;
if (ddlSubject != null)
{
DataSet ds = GetControlData("ddlSubject");
ddlSubject.DataSource = ds.Tables[8];
ddlSubject.DataTextField = "SubjectDesc";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
ddlSubject.Items.FindByValue((e.Row.FindControl("lblSubject") as Label).Text).Selected = true;
}
}
}
lblSubject is populated by another query in GetControlData().
When the debugger gets to the ddlSubject.Items.FindByValue code, I get a NullReferenceException even though lblSubject has a value.
I wonder if I need to change the gridview event for which I'm loading the data.
(e.Row.FindControl("lblSubject") as Label)that is null, or the result ofFindByValue? And are you certain that the text value of lblSubject (which you say is set by another query) does exist in the list of items that the drop down list gets populated by?