Saranya
Saranya

Reputation: 1151

How to set dropdown list value and item as database table value in edit?

When I click edit button the form filling database values in textbox as well as dropdown list..

Textbox values is set. But I can't set dropdownlist values..

The code is;

SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
string str = "Select * from Master where Id='" + id + "'";
SqlCommand command = new SqlCommand(str, con);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
      ddCustomerName.DataValueField = reader["CustomerId"].ToString();
      txtPickupLocation.Text = reader["Location"].ToString();
}
con.Close();   

Upvotes: 0

Views: 5596

Answers (3)

Neeraj
Neeraj

Reputation: 4489

Hey Saranya earlier post is perfect but it gives error if Dropdown values not matched with DB value or if Dropdown havn't value which is return by Db ,So Safer side always checks null value also.

Please Use this code

if (ddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()) != null)
        dddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()).selected = true;

Upvotes: 2

Anuj
Anuj

Reputation: 1526

you have to make the CustomerId in the list selected,for that you have to write

ddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()).selected=true;

instead of

 ddCustomerName.DataValueField = reader["CustomerId"].ToString();

Upvotes: 2

Shafqat Masood
Shafqat Masood

Reputation: 2570

use selectedvalue property

while (reader.Read())
{
    ddCustomerName.SelectedValue= reader["CustomerId"].ToString();
    txtPickupLocation.Text = reader["Location"].ToString();
}

Upvotes: 1

Related Questions