且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过选择下拉列表将数据库值放入文本框中

更新时间:2023-11-27 10:20:10

在最后一行使用下面的代码



 TextBox1.Text = dt1.Rows [ 0 ] [ 0 ]。ToString(); 


试试这个



  protected   void  DropDownList1_SelectedIndexChanged( object  sender,EventArgs e) 
{

SqlConnection con1 = new SqlConnection( 您的连接字符串);
SqlCommand cmd1 = new SqlCommand( select item_price from quantity where item_name = @ item,con1);
cmd1.Parameters.Add( @ item,DropDownList1.SelectedItem.Text);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt1 = new DataTable();
sda1.Fill(dt1);
if (dt1.Rows.Count > 0 // 验证以避免索引异常。
TextBox1.Text = dt1.Rows [ 0 ] [ item_price]的ToString(); // 定义列名
}





你应该知道 SQL注入 [ ^ ] 硬编码 SQl Statemetns


I am using dropdownlist and that has item retriveing from database, my question is that item select any one item that item value will display at text box?

What I have tried:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{

    SqlConnection con1 = new SqlConnection("Data Source=XENORIX8-PC;Initial Catalog=xenorix;User ID=******;Password=*****");
    SqlCommand cmd1 = new SqlCommand("select item_price from quantity where item_name='" + DropDownList1.SelectedItem.Text + "'", con1);
    SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
    DataTable dt1 = new DataTable();
    sda1.Fill(dt1);
    TextBox1.Text = dt1.Rows[0].ToString();
}


Is this correct or not?, If its wrong please send any clue or code

use below code in last line

TextBox1.Text = dt1.Rows[0][0].ToString();


Try this

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
       {

           SqlConnection con1 = new SqlConnection("Your Connection string");
           SqlCommand cmd1 = new SqlCommand("select item_price from quantity where item_name=@item", con1);
           cmd1.Parameters.Add("@item", DropDownList1.SelectedItem.Text);
           SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
           DataTable dt1 = new DataTable();
           sda1.Fill(dt1);
           if (dt1.Rows.Count > 0) // validate for avoiding index exception.
               TextBox1.Text = dt1.Rows[0]["item_price"].ToString(); // define the column name
       }



You should be aware of SQL Injection[^] when hardcoding the SQl Statemetns