Hi theunclevince,
How are you binding DropDownList based on GridView column record status.
If you are doing this way, then the final DropDownList will be populated based on the last record of GridView.
That might be the reason for which you are getting error.
So, kindly explain what you are trying to do in detail.
-------------
Cause of Error
The error you are getting because there is a possiblity that you will not get a desired value for each case.
For example:
If User_Status in GridView is OK and your first case gets executed because of the right match, then you will definitely get error because inside that case statement you are inserting KO as Value and Text and you are trying to make that value of item selected which is not yet added to the DropDownList i.e. OK.
Solution
You can do one thing,
You can add that User_Status also to DropDownList but you will get error i.e. Cannot have multiple items selected in a DropDownList
For that, you need to clear previous selection of DropDownList.
IMPORTANT: Also you should make item selected after adding items not before adding items.
Refer below code.
HTML Markup
<asp:GridView ID="gvStatus" runat="server" OnRowDataBound="OnRowDataBound"></asp:GridView>
<br />
<asp:DropDownList ID="ddl_Status" runat="server"></asp:DropDownList>
Code
Binding GridView with Dummy data.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//Dummy Data
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("StatusId"), new DataColumn("User_Status") });
dt.Rows.Add(1, "OK");
dt.Rows.Add(2, "KO");
dt.Rows.Add(3, null);
dt.Rows.Add(4, "OK");
dt.Rows.Add(5, "KO");
gvStatus.DataSource = dt;
gvStatus.DataBind();
}
}
OnRowDataBound
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string User_Status = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "User_Status"));
switch (User_Status)
{
case "OK":
ddl_Status.Items.Insert(0, new ListItem("[ === === === ]", ""));
ddl_Status.Items.Insert(1, new ListItem("KO", "KO"));
ddl_Status.Items.Insert(2, new ListItem(User_Status, User_Status));
//Clearing Previous selection
ddl_Status.ClearSelection();
ddl_Status.Items.FindByValue(User_Status).Selected = true;
break;
case "KO":
ddl_Status.Items.Insert(0, new ListItem("[ === === === ]", ""));
ddl_Status.Items.Insert(1, new ListItem("OK", "OK"));
ddl_Status.Items.Insert(2, new ListItem(User_Status, User_Status));
ddl_Status.ClearSelection();
ddl_Status.Items.FindByValue(User_Status).Selected = true;
break;
case null:
ddl_Status.Items.Insert(0, new ListItem("[ === === === ]", ""));
ddl_Status.Items.Insert(1, new ListItem("OK", "OK"));
ddl_Status.Items.Insert(2, new ListItem("KO", "KO"));
break;
}
}
}
Scrrenshot
Glad to assist!