Jadual Kandungan
Syntax of C# Data Grid View
Examples of C# Data Grid View
Example #5
Conclusion

Paparan Grid Data C#

Sep 03, 2024 pm 03:32 PM
c# c# tutorial

One of the important tasks of a programmer is to fetch details or information stored in a database and display in on the UI/Screen. This is achieved in c# windows forms using DataGrid view control. This control acts as an interface between the UI layer and database layer and fetches the information from the DB and displays it on the screen in a tabular/grid view format. The data grid view is used to display both editable and read-only views. Each value in a data grid is present in a cell and the cell is the fundamental unit of interaction. This article will explain in detail about Data Grid view and its usage. In this topic, we are going to learn about C# Data Grid View.

Syntax of C# Data Grid View

There is no actual syntax as such for the data grid view. It is present in the namespace System.Windows.Forms and assembly that is associated with it is System.Windows.Forms.dll. It is always not necessary to have a data connection to a data source. Even without a data source, rows and columns with respective data can be created and can be added to the data grid view using rows and columns properties.

Steps involved in Binding Database data to a DataGrid View:

  • Establish a connection to the database
  • Create a data adapter(This generally defines the query to be used)
  • Create a data table
  • Fil the data table with the result returned from the data adapter
  • Bind the data table to the grid view
  • Close the connection

Examples of C# Data Grid View

Here are the following examples mention below

Example #1

Connect to SQL Database Table and Display Information

Input:

string sqlconstr = "Data Source=.;Initial Catalog=Test;Integrated Security=True";
string qu = "SELECT * FROM Test";
SqlConnection cx = new SqlConnection(sqlconstr);
SqlDataAdapter dt = new SqlDataAdapter(qu, cx);
DataSet dase = new DataSet();
cx.Open();
dt.Fill(ds, "Test_table");
cx.Close();
dgvt.DataSource = dase;
dgvt.DataMember = "Test_table";
Salin selepas log masuk

The above is the sample code to fetch information from the sql database table and bind it to a data grid view.

As you can see, the first line contains the sql server information. “.” Represents the local server. The initial catalog denotes the database name and integrated security denotes windows authentication. Next is defining the query that needs to be executed on the table. That is the query string. Then a sql connection is established. Then a data adapter is created, which will run the query and get the results. Then this result is filled in the data set. This data set is then bounded to the grid view. Before binding the connection is closed.

Output:

Paparan Grid Data C#

Example #2

Writing Output of Data grid to a text file

Input:

private void outputgrid()
{
//Establishing connection
OleDbDatardr rdr;
OleDbCommand command1=new OleDbCommand();
this.oleDbConnection1.Open();
//query to be executed
command1.ctxt="SELECT FirstName, LastName, Phone, City FROM ptable";
command1.Connection=this.oleDbConnection1;
using (Streamwtr wtr = new Streamwtr("C:\\op.txt",false))
{
while (rdr.Read())
{
wtr.Write(rdr["LastName"]);
wtr.Write("***");
wtr.Write(rdr["FirstName"]);
wtr.Write("***");
wtr.Write(rdr["City"]);
wtr.Write("***");
wtr.Write(rdr["Phone"]);
wtr.WriteLine(); //next new line
}//while
}
}
Salin selepas log masuk

Output:

Paparan Grid Data C#

Example #3

Populating a data grid from excel and export a data grid to excel

Input: 

private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection mycon;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter mycmd;
mycon = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\test.xls';Extended Properties=Excel 8.0;");
mycmd = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", mycon);
mycmd.TableMappings.Add("test", "excel data");
DtSet = new System.Data.DataSet();
mycmd.Fill(DtSet);
dataGridView1.DataSource = DtSet.test[0];
mycon.Close();
}
private void exportoexcel(object sender, EventArgs e)
{
Excel.Application appli;
Excel.Workbook WB;
Excel.Worksheet WS;
object mv = System.Reflection.Missing.Value;
Int16 i, j;
appli = new Excel.ApplicationClass();
WB = appli.Workbooks.Add(mv);
WS = (Excel.Worksheet)WB.Worksheets.get_Item(1);
for (i = 0; i <= dataGridView1.RowCount - 2; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
WS.Cells[i + 1, j + 1] = dataGridView1[j, i].Value.ToString();
}
}
WB.SaveAs(@"c:\test.xls", Excel.XlFileFormat.WBNormal, mv, mv, mv, mv, Excel.XlSaveAsAccessMode.xlExclusive, mv, mv, mv, mv, mv);
WB.Close(true, mv, mv);
appli.Quit();
releaseObject(WS);
releaseObject(WB);
releaseObject(appli);
}
Salin selepas log masuk

Output:

Paparan Grid Data C#

Example #4

Adding a row to data grid via a button click without DB

Input:

public void createnewrow()
{
DataTable dtab = new DataTable();
DataColumn col1 = new DataColumn("Name", typeof(string));
DataColumn col2 = new DataColumn("Subject1", typeof(int));
DataColumn col3 = new DataColumn("Subject2", typeof(int));
DataColumn col4 = new DataColumn("Subject3", typeof(int));
DataColumn col5 = new DataColumn("Subject4", typeof(int));
DataColumn col6 = new DataColumn("Subject5", typeof(int));
DataColumn col7 = new DataColumn("Subject6", typeof(int));
DataColumn col8 = new DataColumn("Subject7", typeof(int));
DataColumn col9 = new DataColumn("Subject8", typeof(int));
dtab.Columns.Add(col1);
dtab.Columns.Add(col2);
dtab.Columns.Add(col3);
dtab.Columns.Add(col4);
dtab.Columns.Add(col5);
dtab.Columns.Add(col6);
dtab.Columns.Add(col7);
dtab.Columns.Add(col8);
dtab.Columns.Add(col9);
dtab.Rows.Add("Vk",12,23,45,67,89,90,78,80);
dtab.Rows.Add("Vksdfsdf",45,23,65,67,99,30,78,50);
dtab.Rows.Add("test1",42,33,45,70,29,90,78,40);
dataGridView1.DataSource = dtab;
}
Salin selepas log masuk

Example #5

Creating a data grid from an xml file and saving data grid to an xml file

Import XML to data grid view

Input:

private void readfromxml()
{
try
{
XmlReader xip ;
xip = XmlReader.Create("test.xml", new XmlReaderSettings());
DataSet ds = new DataSet();
ds.ReadXml(xip);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
Salin selepas log masuk

Export Data Grid to XML

Input:

private void exportotxml()
{
DataSet ds = new DataSet();
dt = new DataTable();
dt.Columns.Add(new DataColumn("sub1", Type.GetType("System.Int32")));
dt.Columns.Add(new DataColumn("sub2", Type.GetType("System.Int32")));
dt.Columns.Add(new DataColumn("sub3", Type.GetType("System.Int32")));
fillRows(22, 22, 22);
fillRows(33, 33, 33);
fillRows(44, 44, 44);
fillRows(55, 55, 55);
ds.Tables.Add(dt);
ds.Tables[0].TableName = "test";
ds.WriteXml("test.xml");
}
private void createrows(int sub1, string sub2, int sub3)
{
DataRow dr ;
dr = dt.NewRow();
dr["sub1"] = sub1;
dr["sub2"] = sub2;
dr["sub3"] = sub3;
dt.Rows.Add(dr);
}
Salin selepas log masuk

Conclusion

Thus, the article covered in detail the data grid view in c#. It showed various examples like how a data grid view can be loaded from the sql database or an excel file. It also showed how a grid view data can be exported to an excel file or csv file. It also showed how a data grid can be populated without a DB or a data source. It also showed how a new row can be added to a table via a button click. It also explained in detail about the way xml data can be imported into a grid view and how data grid values can be exported into the xml file. To learn more in detail, it would be advisable to write sample programs and practice them.

Atas ialah kandungan terperinci Paparan Grid Data C#. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn

Alat AI Hot

Undresser.AI Undress

Undresser.AI Undress

Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover

AI Clothes Remover

Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool

Undress AI Tool

Gambar buka pakaian secara percuma

Clothoff.io

Clothoff.io

Penyingkiran pakaian AI

AI Hentai Generator

AI Hentai Generator

Menjana ai hentai secara percuma.

Artikel Panas

R.E.P.O. Kristal tenaga dijelaskan dan apa yang mereka lakukan (kristal kuning)
3 minggu yang lalu By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Tetapan grafik terbaik
3 minggu yang lalu By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Cara Memperbaiki Audio Jika anda tidak dapat mendengar sesiapa
3 minggu yang lalu By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: Cara Membuka Segala -galanya Di Myrise
4 minggu yang lalu By 尊渡假赌尊渡假赌尊渡假赌

Alat panas

Notepad++7.3.1

Notepad++7.3.1

Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina

SublimeText3 versi Cina

Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1

Hantar Studio 13.0.1

Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6

Dreamweaver CS6

Alat pembangunan web visual

SublimeText3 versi Mac

SublimeText3 versi Mac

Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Direktori Aktif dengan C# Direktori Aktif dengan C# Sep 03, 2024 pm 03:33 PM

Panduan untuk Active Directory dengan C#. Di sini kita membincangkan pengenalan dan cara Active Directory berfungsi dalam C# bersama-sama dengan sintaks dan contoh.

Penjana Nombor Rawak dalam C# Penjana Nombor Rawak dalam C# Sep 03, 2024 pm 03:34 PM

Panduan untuk Penjana Nombor Rawak dalam C#. Di sini kita membincangkan cara Penjana Nombor Rawak berfungsi, konsep nombor pseudo-rawak dan selamat.

C# Serialisasi C# Serialisasi Sep 03, 2024 pm 03:30 PM

Panduan untuk Pensirian C#. Di sini kita membincangkan pengenalan, langkah-langkah objek siri C#, kerja, dan contoh masing-masing.

Paparan Grid Data C# Paparan Grid Data C# Sep 03, 2024 pm 03:32 PM

Panduan untuk Paparan Grid Data C#. Di sini kita membincangkan contoh cara paparan grid data boleh dimuatkan dan dieksport daripada pangkalan data SQL atau fail excel.

Nombor Perdana dalam C# Nombor Perdana dalam C# Sep 03, 2024 pm 03:35 PM

Panduan Nombor Perdana dalam C#. Di sini kita membincangkan pengenalan dan contoh nombor perdana dalam c# bersama dengan pelaksanaan kod.

Corak dalam C# Corak dalam C# Sep 03, 2024 pm 03:33 PM

Panduan kepada Corak dalam C#. Di sini kita membincangkan pengenalan dan 3 jenis Corak teratas dalam C# bersama-sama dengan contoh dan pelaksanaan kodnya.

Faktorial dalam C# Faktorial dalam C# Sep 03, 2024 pm 03:34 PM

Panduan untuk Faktorial dalam C#. Di sini kita membincangkan pengenalan kepada faktorial dalam c# bersama-sama dengan contoh dan pelaksanaan kod yang berbeza.

Perbezaan antara multithreading dan asynchronous C# Perbezaan antara multithreading dan asynchronous C# Apr 03, 2025 pm 02:57 PM

Perbezaan antara multithreading dan asynchronous adalah bahawa multithreading melaksanakan pelbagai benang pada masa yang sama, sementara secara tidak sengaja melakukan operasi tanpa menyekat benang semasa. Multithreading digunakan untuk tugas-tugas yang berintensifkan, sementara asynchronously digunakan untuk interaksi pengguna. Kelebihan multi-threading adalah untuk meningkatkan prestasi pengkomputeran, sementara kelebihan asynchronous adalah untuk tidak menghalang benang UI. Memilih multithreading atau asynchronous bergantung kepada sifat tugas: tugas-tugas intensif pengiraan menggunakan multithreading, tugas yang berinteraksi dengan sumber luaran dan perlu menyimpan respons UI menggunakan asynchronous.

See all articles