开发者

Populate DropDownList from WebDataGrid

I have a WebDataGrid linked to a SqlDataSource to display data. When a row is selected, I want to populate some textboxes and dropdownlists with the data from that row, fo开发者_开发问答r editing purposes. The textboxes work fine; I use the following code to select the second field in the grid (Date) and populate the corresponding textbox (I'm using VB):

txtDate.Text = currentRow.Items(2).Value

However, when I try to populate the dropdownlists using the same code structure, I get the following error:

'ddlType' has a SelectedValue which is invalid because it does not exist in the list of items.

I think the problem may be that the dropdownlists are populated using type_id, while the grid displays type_name. Would this be causing the problem, and is there a way to get around this?


There are couple of things you could try:

  1. Change the SQLDataSource to return the type_id also and set the column to visible="false" that way you could select that field instead of the name and use that for .SelectedValue.

  2. If that is not possible then you could use code like this (this will only work if the text that is displayed in the drop down is unique and is exactly the same as what is displayed in the grid view):

    'replace this with the call to currentRow.Items(#).Value
    Dim sometext As String = "type_name"

    DropDownListName.Items.FindByText(sometext).Selected = True

  3. The other possibility is to loop through each element in the drop down and find the text, this is like the brute force method but works.

    'replace this with the call to currentRow.Items(#).Value

    Dim sometext As String = "type_name"

    For Each ddItem As ListItem In ddArriveAMPM.Items

     `If String.Compare(sometext, ddItem.Text, True) = 1 Then`   
         `ddItem.Selected = True`
      `End If`        
    `Next`
    


You have to add the item to the listbox before you can select it.

DropDownListX.Items.Add("Item");

or

DropDownListX.Items.Add(new ListItem("String","Value"));

Make sure to clear the DropDown box when selecting a new row otherwise the old rows values will stay in there.

DropDownListX.Items.Clear();

After this you can use SelectedValue

Cheers, Stefan

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜