I have this DropDownlist
Screenshot:
and what I want to do is to change the displayed text of the DropDownList
based on the selected table row. I have this code below but it is not working. I am using C# and ASP.NET btw.
C# Code:
drpDepartment.DataTextField = grdRecentCases.SelectedRow.Cells[1].Text;
drpCharge.DataTextField = grdRecentCases.SelectedRow.Cells[2].Text;
CodePudding user response:
You can use Text to change the value of the 2 drop downs (ddl, drop down list), but ONLY if the ddl's downs are SINGLE column drop downs. If the dropdown has TWO columns, and they OFTEN do, such as "ID" and Department, but you ONLY display the department text, but the first "id" column drives the dropdown?
Then when ddl has or is bound to two columns, then you MUST set the Text value by the "ID" (the hidden column of the ddl).
In your case, it looks like you ONLY have the "text" from the grid, and thus you have to use a .find in the ddl for this purpose.
Example:
This data for drop hotels:
So, our markup:
<h3>Select Hotel</h3>
<asp:DropDownList ID="drpHotels" runat="server"
DataValueField="ID"
DataTextField="HotelName"
AppendDataBoundItems="true" Width="130px" >
<asp:ListItem Text="Select" Value="0"></asp:ListItem>
</asp:DropDownList>
And our code to load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadDrops();
}
void LoadDrops()
{
DataTable rstOptions =
MyRst("SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName");
drpHotels.DataSource = rstOptions;
drpHotels.DataBind();
}
And now we have this:
So, in code behind, say I want to set the ddl to "Swiss Village"?
I can NOT go
drpHotels.Text = "Swiss Village"
(the ddl has TWO columns).
However, I CAN go:
drpHotels.Text = "6"; // Swiss Village PK (id) is 6 from table
So, you have a choice here:
You can either take the text value, query the database based on that real text value from the grid, translate into a "id", and shove that into the text property.
Or, you can do a "find" on the ddl like this based on the text value.
string strTest = "Swiss Village";
drpHotels.ClearSelection();
drpHotels.Items.FindByText(strTest).Selected = true;
So, either you set the ddl by the "id" or first hidden column you have, or you use the above to "find" the item by the "text" value (2nd column) as per above.