happyman
happyman

Reputation: 21

How do I put Dropdownbox DataValueField value into variable?

I am trying to get the value from DropDownlist.DataValueField to the contact_id variable so i can then read the rest of the data of the id selected from the dropdownlist. This is my example code:

string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

            SqlConnection con = new SqlConnection(str);
            string com = "Select * from Product";
            SqlDataAdapter adpt = new SqlDataAdapter(com, con);
            DataTable dt = new DataTable();
            adpt.Fill(dt);
            DropDownList1.DataSource = dt;
            DropDownList1.DataBind();
            DropDownList1.DataTextField = "Product_Name";
            DropDownList1.DataValueField = "Id";
            DropDownList1.DataBind();

            String contact_id = DropDownList1.DataValueField.Trim();

            Textbox1.Text = contact_id;

I expect the value in dropdownlist1.DataValueField to be kept in contact_id variable. But instead, nothing shows up in Textbox1.

Upvotes: 0

Views: 136

Answers (1)

d4zed
d4zed

Reputation: 496

You can use the SelectedValue property…

// set
DropDownList1.SelectedValue = "1";
// get
string value = DropDownList1.SelectedValue;

Upvotes: 1

Related Questions