0

is it possible to populate a Gridview table using a c# function? For Gridview usually I see DataSource and SqlDataSource with the queries after to retrieve the data.

I already have a List of objects each with fields that should populate my table. Each object has 9 string fields and each should be bound to a column. Each object in the list essentially represents a row in the table. Would the code in the c# file be something like this?

for (int i = 0; i < credentials.Count; i++)
{
    for (int j = 0; j < 10; j++)
    {
        row1["ID"] = credentials[i].Id.ToString();
        row1["Windows ID"] = credentials[i].WindowsId;
        row1["First Name"] = credentials[i].FirstName.ToString();
        row1["Last Name"] = credentials[i].LastName.ToString();
        ...

        dt.Rows.Add(row1);
    }


}
gridRoles.DataSource = dt;
gridRoles.DataBind();
2
  • yes it looks like it should work. I've been filling gridviews on they fly many times. Commented Jun 17, 2016 at 19:05
  • I am not sure about asp.net but usually I set my source to the list of objects, and I write in my xaml the specific fieldName I would like to show in each column (FieldName is the member variable of my object: Name, ID, Whatever, .. etc) Commented Jun 17, 2016 at 19:16

5 Answers 5

2

Yes what you are doing looks like it should work, although I'm not sure what you're using j for since it's not used in your above code. The way that I have populated a DataGridView in the past programmatically is by creating a DataTable object:

DataTable dt = new DataTable();

defining its columns:

dt.Columns.Add(columnName);`

creating DataRows:

DataRow row = dt.NewRow();
//fill row
row[columnName or index] = value; //repeat for needed values, could use a for loop and go through indexes

adding the DataRow to the DataTable:

dt.Rows.Add(row);
dt.Rows.InsertAt(row, index); //if you want a specific position

and finally, set the DataGridView's DataSource as the DataTable like you had:

dgv.DataSource = dt;

Note: if you don't have the DataGridView's columns defined the same as the DataRows then things won't work properly.

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

Comments

0

Edit: Other people have been saying that your data should be a source on the gridview. I believe this would work and be much faster. My solution would work for creating new data with the iteration (like say you wanted the ID to match the spot on the gridview.) It may, however be handy to create a new model for your list item and create some getters for the sake of modular OOP.


In this case I would create a new model for your gridview item (looks like users in this case). So I did something similar in UWP and it ended up looking like this:

        ButtonRow = new List<ButtonModel>();
        int daysOnButtonRow = 365;
        TimeSpan additionalDay = new System.TimeSpan(1);
        for (int i = 0; i < daysOnButtonRow; i++)
        {
            ButtonRow.Add(new ButtonModel(DaysFromToday(i),   DaysFromToday(i + 1)));
        }

Then the ButtonModel class contained the parameters specific to each button and getters for relevant information I wanted to display on that button.

public class ButtonModel
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

    public ButtonModel(DateTime _startDate, DateTime _endDate)
    {
        StartDate = _startDate;
        EndDate = _endDate;
    }

    public string StartDateTruncatedName
    {
        get { return StartDate.ToString("dddd").Substring(0, 3).ToUpper(); }
    }

    public string StartDateDayNum
    {
        get { return StartDate.Day.ToString(); }
    }

    public string StartDateMonth
    {
        get { return StartDate.ToString("MMMM").ToUpper(); }
    }
}

This can be a lot cleaner and more modular. The example on a listview, but it should work similarly for a gridview. Since you're already working with a populated list, I would suggest using a 'for-in' loop as well for your iteration instead of the standard 'for' loop. This would make it so every time you add an item to the list, it would be added to the gridview.

Hope this helps! :)

Comments

0

If you already have a List of objects you can just set it as the datasource for the GridView, no need to convert or create a new datatable.

gridRoles.DataSource = credentials;

2 Comments

I have a List but the list is generated differently each time due to searching algorithms. Would I still be able to do that?
I suppose its a list of objects of a custom class, if that is the case there should be no problem, the GridView will expose the properties of each object in your class as the columns and each object will be a row. However if you say that is generated differently, that is the list contains different types you would need to check beforehand, or you could build a model that accommodates the different possibilities.
0

Why cant you use a ObjectDataSource? Specify the class and method in ObjectDatasource's properties and you are all set. Bind the ObjectDatasource to the grid view.

Comments

0
    SqlCommand cmd = new SqlCommand();
    SqlConnection con = new SqlConnection();


       try
        {
            using (SqlConnection con = new SqlConnection("Data Source = [SERVERNAME]; Initial Catalog = CustomerOrders; Integrated Security = true"))
            {
                String name = dropDownList.SelectedItem.Text;
                SqlDataAdapter cmd = new SqlDataAdapter("SELECT * FROM Customer INNER JOIN Orders ON Customer.CustomerID = Orders.ReferenceID WHERE Name = '" + name + "'", con);
                con.Open();
                DataTable dtbl = new DataTable();
                cmd.Fill(dtbl);
                gvPhoneBook.DataSource = dtbl;
                gvPhoneBook.DataBind();

            }
        }
        catch (Exception Ex)
        {
            Console.WriteLine(Ex.Message);
        }

1 Comment

Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.

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.