在标签中显示数据 [英] Show data in label

查看:90
本文介绍了在标签中显示数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的表单

我有一个类连接以连接到数据库

And i have a class Connect to connect to the database

class Connect
{
    SqlConnection con;
    public Connect()
    {
        String connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Application.StartupPath + @"\Database1.mdf;Integrated Security=True;User Instance=True";
        con = new SqlConnection(connectionString);
    }

    public DataTable executeSelect(String query)
    {
        con.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(query, con);
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        con.Close();

        return dt;
    }

    public void execute(String query)
    {

        con.Open();
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.ExecuteNonQuery();

        con.Close();
    }
}

我有 MsProduct databsae中总是有新数据的表。 ComboBox 显示我的项目的名称。我的问题是,当我选择中选择的项目时,我希望我的表单在标签 ProductID Value c $ c> ComboBox 。并且数据与数据库中的数据相同例如,我在组合框中选择蝙蝠侠书,标签将显示其产品ID和ID必须在数据库中相同。你能给我一个代码示例来解决这个问题吗?谢谢

I have MsProducttable in databsae that always have new data. The ComboBox show my items' name. My problems is I want my form to show its Product ID in Label ProductID Valuewhen i choose selected item in ComboBox. And the data is the same with the data in database For example, I select Batman book in combo box, the label will show its Product ID and the ID must be the same in database. Could you please give me the example of code to solve this problem?? Thank you

推荐答案

其实很简单。您只需正确设置 ComboBox

Actually it's pretty simple. You only need to setup your ComboBox properly.

(更新代码以满足评论的额外要求)

(Updated code to meet additional requirement from comment)

Connect connect    = new Connect();
DataTable products = connect.executeSelect(GET_PRODUCTS_TABLE_QUERY);

productComboBox.DataSource    = products;
productComboBox.DisplayMember = "productName";
//removed setting of ValueMember so we can access the whole DataTableRow
//productComboBox.ValueMember   = "productID";

现在您的 ComboBox 他们的姓名和ID。现在,您只需要将所选产品的productID传递到您的标签。
为此,您需要处理 ComboBox SelectedValueChanged 事件:

now your ComboBox has all your products with their names and IDs. Now you only need to pass the productID of the selected product to your label. To do this you need to handle the SelectedValueChanged event of your ComboBox:

private void productComboBox_SelectedValueChanged(object sender, EventArgs e)
{
    //productIdLabel.Text = productComboBox.SelectedValue.ToString();
    DataRowView selectedRow = comboBox1.SelectedValue as DataRowView;

    if (selectedRow != null)
    {
        productIdLabel.Text    = selectedRow["productID"].ToString();
        productPriceLabel.Text = selectedRow["productPrice"].ToString();
        ...
    }
}

这篇关于在标签中显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆