This
article will show you how you can bind datagridview with sql server table using
c#.net in windows
application. In this I have used data table to store the data of sql table
and then display it in gridview by C#.net .
Some of my
previous article is as follows: How
To Convert Text Into Image In C# In Windows Application, Detecting
Ctrl+ V Key Pressed Or Stroke Using C# & VB.Net In Windows Application, Group
CheckBox In C# WinForm, Read
Outlook Email Subject Using c#, Read
Outlook Inbox Mail And Email Count Of Inbox Using C#.Net, How
To Read XML File In DataSet And Display in DataGridview Using C#.Net, WebBrowser
Control in C#, Windows Application, Change
Control Font Size At Runtime / Dynamically Using C#.Net and VB.Net In Windows
Application.
So for this
article first we will create a new windows
application and add the datagridview control in the form.
Now add the
below code into the form.
using System;
using System.Data;
using
System.Data.SqlClient;
using
System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = GetDataFromDataBase();
dataGridView1.DataSource = dt;
}
/// <summary>
/// Get you data
/// </summary>
/// <returns></returns>
public DataTable
GetDataFromDataBase()
{
DataTable dt = new DataTable();
SqlConnection con =
new SqlConnection("----Your connection string-----");
string query = "Select * from CountryTable;";
SqlDataAdapter da = new SqlDataAdapter(query,
con);
da.Fill(dt);
return dt;
}
}
}
|
In above
code I have used a function GetDataFromDataBase. This function will access the
data from the sql database table. Now we will call the data function to bind
the data to datagridview. Now we have done run the application to check the
output.
0 comments:
Please let me know your view