从列表框中选择

时间:2014-03-27 17:06:40

标签: c# select listbox

我是c#编程的新手,我对此感到困惑。我有一个包含产品名称的列表框。我想要做的是在列表框中选择一个项目,并将其数量(整数)放在标签中。我已经尝试使用消息框来获取仅在框中选择的内容,但它不起作用。有人能帮助我吗?

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var conn = new SqlConnection();
        conn.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Onno\Documents\club.mdf;Integrated Security=True;Connect Timeout=30";
        conn.Open();

        var dataset = new DataSet();
        var StockAdapter = new SqlDataAdapter();
        StockAdapter.SelectCommand = new SqlCommand("Select * from Stock", conn);

        dataset.Tables.Add("ProductName");

        StockAdapter.Fill(dataset, "ProductName");

        listBox1.DataSource = dataset.Tables["ProductName"];

        listBox1.DisplayMember = "ProductName";
    }

    private void button2_Click(object sender, EventArgs e)
    {
        var conn = new SqlConnection();
        conn.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Onno\Documents\club.mdf;Integrated Security=True;Connect Timeout=30";
        conn.Open();

        MessageBox.Show("test");
    }

    private void label1_Click(object sender, EventArgs e)
    {

    }

    private void button2_Click_1(object sender, EventArgs e)
    {

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var conn = new SqlConnection();
        conn.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Onno\Documents\club.mdf;Integrated Security=True;Connect Timeout=30";
        conn.Open();
        MessageBox.Show(listBox1.SelectedItem.ToString());
    }

0 个答案:

没有答案