我编写了一个项目,通过单击列表框中的列表在文本框中显示结果。因此,当我单击列表框中的值时,它应该检索结果&数据库中的每一列都应该适合我创建的文本框。
我已经编写了一些代码,但它不起作用。我需要你的帮助
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();
}
我在数据库中有三列(成分,方法,配方)
答案 0 :(得分:0)
在表单加载上设置列表框的内容并将其从SelectedIndexChanged事件中取出,同时添加Listbox数据源。
// Create the event
public void Form_Load()
{
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);
ListBox1.DisplayMember = <one of your recipe table fields (e.g. Name)>;
ListBox1.ValueMember = <one of your recipe table fields (e.g. ID);
}
// Set your textboxes
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// These will all provide the same result, you may need to requery the database for your fields based on an ID.
ing_tx.Text = ListBox1.SelectedValue.ToString();
mx_tx.text = ListBox1.SelectedValue.ToString();
re_tx.text = ListBox1.SelectedValue.ToString();
}
答案 1 :(得分:0)
您将文本框的文本设置为ListBox1.SelectedValue.ToString();
你应该:
ing_tx.Text = ds.Tables[0].Rows[0]["Ingredients"].ToString();
mx_tx.text = ds.Tables[0].Rows[0]["Methods"].ToString();
re_tx.text = ds.Tables[0].Rows[0]["Recipe"].ToString();