Program Included: Modify Program To Get Database Table Into A dataGridView
-
Monday, December 31, 2012 5:52 PM
How can I get data from a table into a datagridview. I'm trying to do this with the below C# program.
Below the code are two screenshots. The first is a screenshot from SQL Server Management Studio and shows a table (t1) in database SamplePubDB. The table has six columns (each column has a header [c1 through c5, rowqguid]). The second screenshot shows that (in the debugger) I can see the headers of table t1.
thanks
using System.Data; using System.Data.SqlClient; using System.Windows.Forms; using System; namespace WindowsFormsApplication1 { public partial class Form1 : Form { static void Main() { MyFillData f = new MyFillData(); f.FillData(); } } public class MyFillData { public void FillData() { string PUBSVR_ESC = @"123ABC0"; string PUBDB = "SamplePubDB"; int pVer; using (SqlConnection c = new SqlConnection("Data Source=" + PUBSVR_ESC + ";Initial Catalog=" + PUBDB + ";" + "Integrated Security=SSPI")) { c.Open(); using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM t1", c)) { DataTable t = new DataTable(); a.Fill(t); // dataGridView1.DataSource = t; // <-- From your designer SqlDataAdapter tempReplicaDataAdapter = new SqlDataAdapter(); tempReplicaDataAdapter.SelectCommand = new SqlCommand( "exec sp_showrowreplicainfo @tablename='t1', @rowguid = '" + "8B126420-F849-E211-B389-D0DF9A3EBB01" + "', @show = 'BOTH'", c); DataSet PubReplicaDataSet = new DataSet("office"); tempReplicaDataAdapter.Fill(PubReplicaDataSet); c.Close(); DataRow pVerRow = PubReplicaDataSet.Tables[0].Select("server_name='" + PUBSVR_ESC + "' and db_name='" + PUBDB + "' and current_state='y'")[0]; // Extract current publisher row version into the pVer variable pVer = Int32.Parse(pVerRow["version"].ToString()); DataRow rowPublisher = PubReplicaDataSet.Tables[0].Rows[0]; } } } } }
All Replies
-
Wednesday, January 02, 2013 2:34 AMModerator
Hi, please refer to the codes on the following document to bind data to datagridview:
http://csharp.net-informations.com/datagridview/csharp-datagridview-sql-server.htm
Allen Li
TechNet Community Support- Marked As Answer by Software Engineering Stuff Wednesday, January 02, 2013 6:04 PM


