1

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 columns? I am stuck in this area

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

sir how get the data from the classs and pass into the grid view
It is done on the last line of the method. Assigning the filled datatable to the grid's DataSource causes the data to appear in the grid. The data should live in the datatable and be accessed there; if you make changes to the datatable the grid will update to show the changes
i used above code working but i need the oop concepts. i have created class above std.i want load data from the class in to datagridview
How about rename the method to GetDataTable, and return dt on the last line instead, then you can do dataGridView1.DataSource = GetDataTable()
please write the code
|
0

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.

1 Comment

can you write the code sir

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.