-3

Possible Duplicate:
listBox selected item

i need to get the particular selected item of the list box which is sourced by a database column and insert the selected item into a new database.? m working in Microsoft Visual Studio 2008 and SQL Server Express

        con.Open();
        DataSet ds = new DataSet();
        SqlDataAdapter adapter = new SqlDataAdapter("SELECT ItemName from tariff", con);
        adapter.Fill(ds);
        this.listBox1.DataSource = ds.Tables[0];
        this.listBox1.DisplayMember = "ItemName";
        con.Close();

        private void btnSave_Click(object sender, EventArgs e)
    {
        con.Open();
        cmd.Connection = con;
        cmd.CommandText = "INSERT INTO logs VALUES('" + txtRoom.Text.ToString() + "','"????????????????????????????"')";
        cmd.ExecuteNonQuery();
        con.Close();
        loadData();
    }
Community
  • 1
  • 1
Akshay
  • 181
  • 1
  • 6
  • 17
  • Read this: http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selectedindexchanged.aspx – RG-3 Oct 03 '12 at 20:30

1 Answers1

1

try

listbox1.SelectedItem.Text

Also: you are setting yourself up for possible SQL Injection. You should take a look at parametrized queries.

Using those would turn your statement into something like this:

cmd.CommandText = "INSERT INTO logs VALUES(@room,@listbox)";
cmd.Parameters.AddWithValue("@room", txtRoom.Text);
cmd.Parameters.AddWithValue("@listbox",listbox1.SelectedItem.Text);
Thousand
  • 6,562
  • 3
  • 38
  • 46