Home > Back-end >  How to load the datagridview using OOP C#
How to load the datagridview using OOP C#

Time:11-24

I am a beginner at C# and .NET oop concepts. I want to load the datagridview. I don't know how to pass the data. What I tried so far I attached below.

I created a class std

public void get()
{
    SqlConnection con = new SqlConnection("server =.; initial catalog=testdb; User ID=sa; Password=123");
    string sql = "select * from std";

    con.Open();

    SqlCommand cm = new SqlCommand(sql, con);
    SqlDataReader dr = cm.ExecuteReader();

    while ( dr.Read())
    {
        string stname = dr["st_name"].ToString();
        string nicnum = dr["nic"].ToString();
    }

    con.Close();
}

Form: I am getting data like this way

 std ss = new std();
 ss.get();

 dataGridView1.Rows.Clear();

           

If I wrote like this way how to pass data into the datagridview coloums? I am stuck in this area

CodePudding user response:

It's easier like this:

    public void FillGrid()
    {
        var dt = new DataTable();
        var da = new SqlDataAdapter("select * from std", "server =.; initial catalog=testdb; User ID=sa; Password=123");
        da.Fill(dt);
        dataGridView1.DataSource = dt;
    }

but if you're going to use such a low level method of database access you should consider adding a DataSet type of file to your project; visual studio will write all this code and more for you with a few mouse clicks, and it makes a good job of creating tables and adapters that are a lot easier to work with

CodePudding user response:

you have made multiple mistakes. First you read data wirh dataraeader and in every iteration define two stname and nimnum variables like. So when loop ends variables are destroyed. You have to define data table and read data by dataraeader and and add them to it row by row. Or read by sqldataadapter and read it immediately and pass to datatable object.Finnaly you pass datatable as return object of function. Use this vala as datasource of datagridview property if I'm not wrong.

  •  Tags:  
  • c#
  • Related