Reputation: 43
This is what my form looks like, and my code looks like this:
using System.Data.SqlClient;
namespace ProjectCSharpSQLserver
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=I:\ProjectCSharpSQLserver\ProjectCSharpSQLserver\CsSQL.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
cn.Open();
SqlDataAdapter sda = new SqlDataAdapter("insert into info (id, Name, phone, Address) Values ('" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "')", cn);
sda.Fill(dt);
cn.Close();
}
}
}
I need to know how to open the combobox, find the Id, choose one and then then textboxes get populated by the data from the db, so I can delete and update data.
Upvotes: 1
Views: 560
Reputation: 5119
I found an example that you can use here.
private void cb1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cb = (ComboBox)sender;
cn.Open();
SqlDataAdapter sda = new SqlDataAdapter("Place your DELETE statement here", cn);
sda.Fill(dt);
cn.Close();
}
This would run the selected statement in the combobox
each time it is changed. As an aside, when you run a SqlDataAdapter, it will automatically open and close a connection to the database for you so you don't have to use cn.Open()
/cn.Close()
. But doing so it still a good habit to get in to.
And just to remind you, I would seriously look into using parameterized queries once you are more comfortable with C# and ADO.NET.
Upvotes: 1