I took an video from you tube to Retrieving Data from SQL Server using C# and ADO.Net
http://www.youtube.com/watch?v=4kBXLv4h2ig&feature=related
I Do the same as him in the video... I want to show data from an sql database in a DataGridView.
I get an error whit
da.Fill(dg);
dg.DataSource = dg.Tables[0];
I name my DataGridView dg
...
Complete code
using System.Data.SqlClient;
namespace SQLconnection
{
public partial class Form1 : Form
{
SqlConnection cs = new SqlConnection("Data Source=FRANK-PC\\SQLEXPRESS; Initial Catalog=Forc#; Integrated Security=TRUE");
SqlDataAdapter da = new SqlDataAdapter();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
da.InsertCommand= new SqlCommand ("INSERT INTO tblContacts VALUES (@FirstName,@LastName)", cs );
da.InsertCommand.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
da.InsertCommand.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastname.Text;
cs.Open();
da.InsertCommand.ExecuteNonQuery();
cs.Close();
}
// Display data in dg
private void button2_Click(object sender, EventArgs e)
{
da.SelectCommand = new SqlCommand("SELECT * FROM tblContacts", cs);
da.Fill(dg);
dg.DataSource = dg.Tables[0];
}
}
}