mysticalstick
mysticalstick

Reputation: 165

populate Gridview using c#

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();

Upvotes: 0

Views: 5316

Answers (5)

Just_Ice
Just_Ice

Reputation: 563

    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);
        }

Upvotes: 0

Arshad Mohammad
Arshad Mohammad

Reputation: 409

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.

Upvotes: 0

Andrew
Andrew

Reputation: 388

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.

Upvotes: 2

ArturoAP
ArturoAP

Reputation: 432

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;

Upvotes: 0

Josh Abrams
Josh Abrams

Reputation: 76

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! :)

Upvotes: 0

Related Questions