C# .NET - Fill the datagridview in C#

Asked By Ananya on 06-May-11 06:48 AM
Hai,

Iam developing a project in windows application in c#.I want to fill the datagridview with dataset and programatically in the same datagridview.How do i add rows programatically to a bound Datagridview.Please help me .
Mitesh Darji replied to Ananya on 06-May-11 06:59 AM
can you please go through below link:

http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx

Imports
System Imports System.Data Imports System.Data.SqlClient Imports System.Windows.Forms Public Class Form1 Inherits System.Windows.Forms.Form Private dataGridView1 As New DataGridView() Private bindingSource1 As New BindingSource() Private dataAdapter As New SqlDataAdapter() Private WithEvents reloadButton As New Button() Private WithEvents submitButton As New Button() <STAThreadAttribute()> _ Public Shared Sub Main() Application.Run(New Form1()) End Sub ' Initialize the form. Public Sub New() Me.dataGridView1.Dock = DockStyle.Fill Me.reloadButton.Text = "reload" Me.submitButton.Text = "submit" Dim panel As New FlowLayoutPanel() panel.Dock = DockStyle.Top panel.AutoSize = True panel.Controls.AddRange(New Control() {Me.reloadButton, Me.submitButton}) Me.Controls.AddRange(New Control() {Me.dataGridView1, panel}) Me.Text = "DataGridView databinding and updating demo" End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load ' Bind the DataGridView to the BindingSource ' and load the data from the database. Me.dataGridView1.DataSource = Me.bindingSource1 GetData("select * from Customers") End Sub Private Sub reloadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles reloadButton.Click ' Reload the data from the database. GetData(Me.dataAdapter.SelectCommand.CommandText) End Sub Private Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles submitButton.Click ' Update the database with the user's changes. Me.dataAdapter.Update(CType(Me.bindingSource1.DataSource, DataTable)) End Sub Private Sub GetData(ByVal selectCommand As String) Try ' Specify a connection string. Replace the given value with a ' valid connection string for a Northwind SQL Server sample ' database accessible to your system. Dim connectionString As String = _ "Integrated Security=SSPI;Persist Security Info=False;" + _ "Initial Catalog=Northwind;Data Source=localhost" ' Create a new data adapter based on the specified query. Me.dataAdapter = New SqlDataAdapter(selectCommand, connectionString) ' Create a command builder to generate SQL update, insert, and ' delete commands based on selectCommand. These are used to ' update the database. Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapter) ' Populate a new data table and bind it to the BindingSource. Dim table As New DataTable() table.Locale = System.Globalization.CultureInfo.InvariantCulture Me.dataAdapter.Fill(table) Me.bindingSource1.DataSource = table ' Resize the DataGridView columns to fit the newly loaded content. Me.dataGridView1.AutoResizeColumns( _ DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader) Catch ex As SqlException MessageBox.Show("To run this example, replace the value of the " + _ "connectionString variable with a connection string that is " + _ "valid for your system.") End Try End Sub End Class
Venkat K replied to Ananya on 06-May-11 06:59 AM
Here are the simple steps how you can bind a datagridview from a dataset / datatable.//the DataGridView
 DataGridView dgView = new DataGridView();
 
//BindingSource to sync DataTable and DataGridView
 BindingSource bSource = new BindingSource();
 
//set the BindingSource DataSource
 bSource.DataSource = dTable;
 
//set the DataGridView DataSource
 dgView.DataSource = bSource;

Check this lnk on how to add rows dynamically to datagriview:
http://cplus.about.com/od/learnc/ss/adv_winforms_6.htm

Thanks
dipa ahuja replied to Ananya on 06-May-11 07:01 AM
    public DataGrid()
    {
      InitializeComponent();
      string q = "selete * from table;
      SqlDataAdapter da = new SqlDataAdapter(q, "connectionString");
      DataTable dt = new DataTable();
      da.Fill(dt);
      dataGridView1.DataSource = dt;
        }
and to add in dataGrid:


 dataGridView1.Rows.Add("column1","column2", "column3");
      
Reena Jain replied to Ananya on 06-May-11 07:09 AM
hi,

here is code to add a row to datagridview with textBox columns

DataGridViewRow dgvRow = new DataGridViewRow();
DataGridViewCell dgvCell = default(DataGridViewCell);
 
dgvCell = new DataGridViewTextBoxCell();
dgvCell.Value = "Reena";
dgvRow.Cells.Add(dgvCell);
 
dgvCell = new DataGridViewTextBoxCell();
dgvCell.Value = "Jain";
dgvRow.Cells.Add(dgvCell);
 
DataGridView1.Rows.Add(dgvRow);

Hoe this will help you
Ravi S replied to Ananya on 06-May-11 09:51 AM
HI


try this code

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=your .mdb file;";
            string sql = "SELECT * FROM Authors";
            OleDbConnection connection = new OleDbConnection(connetionString);
            OleDbDataAdapter dataadapter = new OleDbDataAdapter(sql, connection);
            DataSet ds = new DataSet();
            connection.Open();
            dataadapter.Fill(ds, "Authors_table");
            connection.Close();
            dataGridView1.DataSource = ds;
            dataGridView1.DataMember = "Authors_table";
        }
    }
}


hope it helps you...
Nikhil Mahajan replied to Ananya on 06-May-11 11:33 PM
try the below code to bind datagridview programatically with dataset

//This connection string is used to connect to database
String strConnection = "Data Source=MYSYSTEM;Initial Catalog=MySamplesDB;Integrated Security=True";
//Establish SQL Connection
SqlConnection con = new SqlConnection(strConnection);
//Open database connection to connect to SQL Server
con.Open();
//Data table is used to bind the resultant data
DataTable dtusers = new DataTable();
// Create a new data adapter based on the specified query.
SqlDataAdapter da = new SqlDataAdapter("Select * from User_Information", con);
//SQl command builder is used to get data from database based on query
SqlCommandBuilder cmd = new SqlCommandBuilder(da);
//Fill data table
da.Fill(dtusers);
//assigning data table to Datagridview
dataGridView1.DataSource = dtusers;
//Resize the Datagridview column to fit the gridview columns with data in datagridview
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();



and to add row to datagridview programatically  you need to set the AllowUserToAddRows to false
try below code

public partial class DGVAddNewRowProgrammatically : Form
  {
    public DGVAddNewRowProgrammatically()
    {
      InitializeComponent();
    }
  
    DataTable dt = new DataTable();
    private void DGVAddNewRowProgrammatically_Load(object sender, EventArgs e)
    {
      dt.Columns.Add("a");
      dt.Columns.Add("b");      
      dt.Columns[1].AllowDBNull = false;
      for (int i = 0; i < 10; i++)
      {
        dt.Rows.Add("a" + i.ToString(), "b" + i.ToString());
      }
  
      this.dataGridView1.DataSource = dt;
      this.dataGridView1.AllowUserToAddRows = false;
  
    }
  
    private void AddBt_Click(object sender, EventArgs e)
    {
      DataRow dr = this.dt.NewRow();
      dr["a"] = "ax";
      dr["b"] = "add item";
      dt.Rows.Add(dr);
    }
  }