Emre Aslan
Emre Aslan

Reputation: 45

How to get DataValueField from dropdownlist?

I want to get data from dropdownlist selected item with sql server.But it's don't working.

My asp.net desing codes:

<asp:DropDownList ID="drp_SiparisYazan" runat="server" DataSourceID="SqlDataSourceSiparisYazan" DataTextField="ACIKLAMA" DataValueField="KOD"></asp:DropDownList>       
<asp:SqlDataSource runat="server" ID="SqlDataSourceSiparisYazan" ConnectionString='<%$ ConnectionStrings:.. %>' SelectCommand="SELECT  ...'"></asp:SqlDataSource>

Now I putting valuefield from sqlserver.After It is returning null value in selecteditem.Value.

protected void btnSave_Click(object sender, EventArgs e)
{
    con.Open();
    SqlCommand cmdSave = new SqlCommand(CommandText, con);
    cmdSave.Parameters.AddWithValue("@siparisyazan", drp_SiparisYazan.SelectedItem.Value);
}

Upvotes: 3

Views: 3247

Answers (3)

Tran Anh Hien
Tran Anh Hien

Reputation: 757

 <asp:DropDownList runat="server" ID="ddl" DataValueField="ID" DataTextField="Text"></asp:DropDownList>

(object have ID, Text,...)

and bind List to ddl:ddl.DataSource = list<object> get value use: ddl.SelectedValue

Upvotes: 1

Masoud Andalibi
Masoud Andalibi

Reputation: 3228

Greetings you can use

string value = DropDownList3.SelectedValue;

and insert the value to your database.

Update:

Bind your SqlDataSource's SelectCommand in your code behind in your page_load:

if(!IsPostBack)
{
  SqlDataSourceSiparisYazan.SelectCommand = "Your Query";
  //Make Sure your query is right, trace it with breakpoint
}

And Empty its SelectCommand in your .aspx file:

<asp:SqlDataSource runat="server" ID="SqlDataSourceSiparisYazan" ConnectionString='<%$ ConnectionStrings:CPMMASTER_PGCS %>' SelectCommand=""></asp:SqlDataSource>

Then try to get the SelectedValue.

Second Update: I looked at your Dropdownlist again you didn't bind the KOD to DataValueField (as if its the value?) And you didn't bind the Its Name(Whatever it is) to DataTextField and you expect magically get the value?

Edit your DropdownList Like:

<asp:SqlDataSource runat="server" ID="SqlDataSourceSiparisYazan" DataTextField="Field of the Name to be shown" DataValueField="KOD" ConnectionString='<%$ ConnectionStrings:CPMMASTER_PGCS %>' SelectCommand="SELECT KOD,ACIKLAMA FROM REFKRT ...'"></asp:SqlDataSource>

Upvotes: 3

Hetal Rupareliya
Hetal Rupareliya

Reputation: 387

you can get the selected value of dropdownlist in code behind by using "drp_SiparisYazan.SelectedValue"

Upvotes: 1

Related Questions