我有一个c#表格。我有一个ComboBox作为控制器。我想填充标签以显示与我的下拉列表中所选项目相同的行中的字段。
例如,items是我的ComboBox,所以如果我从我的ComboBox中选择一个项目,那么我希望“description”填充我的标签,因为选择了项目ComboBox。
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql; //Dir used to connect to sql DB
using System.Data.SqlClient; //Dir used to connect to sql DB
namespace items_Form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'syteLine_AppDataSet.item' table. You can move, or remove it, as needed.
this.itemTableAdapter.Fill(this.syteLine_AppDataSet.item);
//creating the connection to database.
SqlConnection con_str = new SqlConnection("Data Source=SL1;Initial Catalog=SyteLine_App;Integrated Security=True");
SqlDataAdapter dta_ad = new SqlDataAdapter("SELECT item, description, lead_time, product_code, p_m_t_code, stocked, matl_type, family_code, low_level, days_supply, order_min, order_mult, plan_code,accept_req, shrink_fact, var_lead, decifld1, decifld2, decifld3, datefld, pass_req, order_max, uf_Active, uf_BoughtOff, uf_Old, uf_ProjectEngineer FROM dbo.item", con_str);
DataTable dta_tbl = new DataTable();
dta_ad.Fill(dta_tbl);
for (int i = 0; i < dta_tbl.Rows.Count; i++)
{
cbxItem.Items.Add(dta_tbl.Rows[i]["item"]);
}
}
public void cbxItem_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbxItem.SelectedIndex == -1)
{
label1.Text = string.Empty;
}
else
{
label1.Text = cbxItem.SelectedItem.ToString();
}
}
}
}
答案 0 :(得分:1)
我只会在页面加载时检索1或2列,只显示下拉列表。
我会在cbxItem_SelectedIndexChanged方法中进行第二次查询,传入所选的值:
DataTable dt = SomeFunctionThatGetsTheDataForTheSelectedValue(cbxItem.SelectedValue)
lblDescription = dt.Rows[0]["Description"];