0
votes

I have an ASP.NET page that contains textboxes, dropdownlists and a gridview. There are two ways to fill in the form, one is when a user selects a row from the gridview the values from the cells populate the textboxes and dropdownlists, the other is the user can directly enter the data into the form. This helps in adding, deleting and updating records from my database. My dropdownlists and gridview are populated with values from a sql statement on the page load event...

DROPDOWNLIST:
 dt = dal.FillDataTable(dbType.SqlServer, "SELECT V_VendorNo + ' | ' + V_VendorName FROM VendorTbl")
    ddlVendorEncum.DataSource = dt
    ddlVendorEncum.DataTextField = dt.Columns.Item(0).ToString
    ddlVendorEncum.DataValueField = dt.Columns.Item(0).ToString
    ddlVendorEncum.DataBind()

GRIDVIEW:
dts = dal.ExecuteSelectStoredPro(dbType.SqlServer, "EncumBugSearch", "@year", lblDef_FY.Text)
    gvEncumbered.DataSource = dts
    gvEncumbered.DataBind()

Because the dropdownlist is a concatentation of two columns from my table, when I select a row in my gridview the value will not populate the dropdownlist with the selected value. Is there a way to do a reverse type concatenation to get the dropdownlist to populate? I tried this:

ddlVendorEncum.Text = gvEncumbered.SelectedRow.Cells(1).ToString

which is the way I populate the textboxes but I get an error.

2

2 Answers

0
votes

You could use

string s = dt.Columns.Item(0).ToString().Split("|".ToCharArray());

and then use the first item in the array (s[0]), but that's the hard way. There's a much easier way.


Change

SELECT V_VendorNo + ' | ' + V_VendorName FROM VendorTbl

to

SELECT V_VendorNo + ' | ' + V_VendorName, VendorNo FROM VendorTbl

and then set the DataValueField to the second field returend from the query.

ddlVendorEncum.DataTextField = dt.Columns.Item(0).ToString 
ddlVendorEncum.DataValueField = dt.Columns.Item(1).ToString 

(Assuming VendorNo isthe primary key.)

0
votes

I think you need to CAST as you are using two different Datatypes in your sql statement

SELECT CAST(V_VendorNo AS Char(10)) + ' | ' + V_VendorName FROM VendorTbl

I am assuming V_VendorNo is Int type in your DB

Try it.