Reputation: 777
I am working on ASP.NET C# web application. I have a DropDownList
for selecting machines_names
that is Databound. And a gridview
which displays stored data. Gridview
also contains templateField
for Edit and Delete Buttons. When Edit Button is clicked the stored values of respective fields must be must be loaded on respective field in web form. The problem is when I click edit button, item in ddl (the default value "--select--") is replaced by current data.
I want the stored ddl item to be selected in the ddl when the edit button is clicked. For example in ddl there are items such as
--select--
Roller
Heater
sensor
In grid view I have the following
Repair-id machine
1 roller
2 sensor
So when I click edit button of ID 2 in grid view, the ddl must select the third item ie sensor without replacing the top item in ddl.
Here's my code
protected DataTable bindMachineName()
{
DataTable dt = new DataTable();
dc.Company_code = Convert.ToInt32(Session["Company_Code"].ToString());
dt = dpbll.select_machine_name(dc);
ddlMachine.DataSource = dt;
ddlMachine.DataTextField = "machine_name";
ddlMachine.DataValueField = "machine_id";
ddlMachine.DataBind();
ddlMachine.Items.Insert(0, new ListItem("----- Select -----", "-1"));
return dt;
}
protected void btnEdit_Click(object sender, EventArgs e)
{
dc.Company_code = Convert.ToInt32(Session["company_code"].ToString());
Button btn = (Button)sender;
GridViewRow gv = (GridViewRow)btn.NamingContainer;
string repair_id = gv.Cells[0].Text;
ViewState["repair_id"] = repair_id;
ddlMachine.SelectedItem.Text = gv.Cells[1].Text;
}
Upvotes: 1
Views: 2760
Reputation: 777
Nevermind I solved the problem.
ddlMachine.Items.FindByText(gv.Cells[1].Text
did work perfectly.
protected void btnEdit_Click(object sender, EventArgs e)
{
dc.Company_code = Convert.ToInt32(Session["company_code"].ToString());
Button btn = (Button)sender;
GridViewRow gv = (GridViewRow)btn.NamingContainer;
string repair_id = gv.Cells[0].Text;
ViewState["repair_id"] = repair_id;
ddlMachine.SelectedIndex=ddlMachine.Items.IndexOf(ddlMachine.Items.FindByText(gv.Cells[1].Text));
}
Upvotes: 1
Reputation: 460108
The problem is when I click edit button, item in ddl (the default value "--select--") is replaced by current data.
You might want to set the DropDownList
's AppendDataBoundItems
to true
.
<asp:DropDownList runat="server" ID="ddlMachine" AppendDataBoundItems="true">
<asp:ListItem Text="----- Select -----" Value="-1" />
</asp:DropDownList>
The
AppendDataBoundItems
property allows you to add items to the ListControl object before data binding occurs. After data binding, the items collection contains both the items from the data source and the previously added items.
Upvotes: 0