从列表框中检索数据并在文本框中显示

从列表框中检索数据并在文本框中显示

问题描述:

我编写了一个项目,通过单击列表框中的列表在文本框中显示结果。因此,当我单击列表框中的值时,它应该检索结果&数据库中的每一列都应该适合我创建的文本框。



我已经编写了一些代码,但它不起作用。我需要你的帮助





我的数据库由三列组成



我尝试了什么:



I have wrote a project to display the result in textbox by clicking the list in the listbox. So when i click a value in list box, it should retrieve the result & each column from the database should fit into the textbox i created.

I have already wrote some code, but its not working. I need your help


My database consists of three columns

What I have tried:

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        con.Open();
        string s = "select * from recipe";
        //SqlCommand cmd = new SqlCommand("select * from recipe where ('" + ListBox1.SelectedItem.ToString() + "')", con);
        SqlDataAdapter da = new SqlDataAdapter(s, con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        ing_tx.Text = ListBox1.SelectedValue.ToString();
        mx_tx.text = ListBox1.SelectedValue.ToString();
        re_tx.text = ListBox1.SelectedValue.ToString();

        }

好吧,首先你从表中获取每一行。您注释掉的行更接近您的需求,但您应该从不连接字符串以创建SQL查询 - 您应该使用参数化查询 [ ^ ]而不是。



2 - 最好列出列你想要检索而不是使用 * 。首先,我们会知道您的列被称为什么!本文列出了其他原因 - 选择所有列 [ ^ ]



3 - 您正在从数据库填充DataSet,但您没有使用已检索的数据。您也没有检查是否实际检索到任何数据。



这是一个基于你到目前为止的工作解决方案(注意我使用的是DataTable而不是DataSet)

Well, firstly you are getting every row from your table. The line you have commented out is closer to what you need but you should never concatenate strings to create SQL queries - you should use parameterised queries[^] instead.

2 - it is better to list the columns you want to retrieve rather than using *. For a start we would have known what your columns were called! There are other reasons listed on this article - Choosing All Columns[^]

3 - You are filling a DataSet from your database but you are not using the data that you have retrieved. You are also not checking to see if any data was actually retrieved at all.

Here is a working solution based on what you have so far (note I'm using a DataTable not a DataSet)
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (ListBox1.SelectedItem == null) return;

    con.Open();
    string s = "select recipe_name,ingredients,method from recipe where recipe_name=@selectedItem";
    SqlDataAdapter da = new SqlDataAdapter(s, con);
    da.SelectCommand.Parameters.AddWithValue("@selectedItem", ListBox1.SelectedItem);
    DataTable ds = new DataTable();
    da.Fill(ds);
    if (ds.Rows.Count > 0)
    {
        ing_tx.Text = dt.Rows[0]["ingredients"].ToString();
        mx_tx.Text = dt.Rows[0]["method"].ToString();
        re_tx.Text = dt.Rows[0]["recipe_name"].ToString();
    }
}

你需要将col1,col2和col3替换为你桌子上列的实际名称我现在已经把你的实际列名称

You will need to replace col1, col2 and col3 with the actual names of the columns on your tableI've now included your actual columns names