September 17, 2004

Implementing a listbox with columns more than value and description in ASP.Net

I was given a bug today, seemed a really simple one: selected user
role was saved as some other item often. As I studied and found later,
many different listbox items share a same value, for example, even
though we see Cosu Test and EC Test, their associated values are both
'Test', so when postback in .net page, asp.net will automatically
select Cosu Test before saving it to database. And as for those
without duplicated values, their saved fine. That's sometimes we saw
saving ok, sometims not.

I added a textbox named RoleIndex to save currently selected role in
order to fix this bug as below,
function validateForm(){
document.all.RoleIndex.value = document.all.DDLRole.selectedIndex;
}
And to associate this function with button "Save",
document.all.BTSave.onclick = validateForm;
This is added before <>

What's more, in its code-behind vb file, we write code this way,
If Not Me.IsPostBack Then
...
Else
'executes every time, this is a must as viewstate won't
stored values in control attributes
SetDropDownListWithAttribute(Me, DDLRole, "userrole")

If IsNumeric(RoleIndex.Text) Then
If CInt(RoleIndex.Text) > 0 Then
DDLRole.SelectedIndex = RoleIndex.Text
End If
End If
End If

And this is the code to handle multiple columns,
Dim row As DataRow
For Each row In MyData.Tables(0).Rows
DDLControl.Items.Insert(i, "item")
DDLControl.Items(i).Value = row("role_code")
DDLControl.Items(i).Text = row("description")
DDLControl.Items(i).Attributes("division") = row("division")
i = i + 1
Next

That's it.

No comments: