Compdigitec Labs

« | Home | »

ASP.NET GridView All-In-One Quick Reference

By admin | July 17, 2010

Here is a quick collection of snippets where one can quickly lookup the necessities of setting up a GridView for the purposes of displaying information to the viewer through a database (for example, MySQL):

Adding Columns of Data

DataTable dt = new DataTable("Tablename");
// for every row
DataRow dr = dt.NewRow();
dr["Column1"] = "Testing";
dr["Column2"] = "Blah";
dr["Column3"] = "Big Blah";

Binding the Data (and storage across sessions)

DataView dv = new DataView(dt);
Session["data"] = dv;
gridviewctrl.DataSource = dv;

Note: This needs AllowPaging to be set to “true”. The following code goes in the “PageIndexChanging” callback.

gridviewctrl.PageIndex = e.NewPageIndex;
gridviewctrl.DataSource = Session["data"];

Note: This needs AllowSorting to be set to “true” and ensure all columns you want sorted have a “SortExpression” that matches the column name in the DataTable. The following code goes in the “Sorting” callback.

string dir;
if (e.SortDirection == SortDirection.Ascending) {
    dir = "ASC";
} else {
    dir = "DESC";
((DataView)Session["Data"]).Sort = e.SortExpression + " " + dir;
gridviewctrl.DataSource = Session["data"];

Create a <asp:ButtonField> declaration as follows: <asp:ButtonField ButtonType=”Button” Text=”Button Text Here” CommandName=”DoSomething” />

if (e.CommandName == "DoSomething") {
    // get Index
    int index = Convert.ToInt32(e.CommandArgument);
    string test = ((DataView)Session["Data"]).Table.Rows[index]["Column1"];
    Response.Redirect("" + test.ToString()");

If you found this article helpful or interesting, please help Compdigitec spread the word. Don’t forget to subscribe to Compdigitec Labs for more useful and interesting articles!

Topics: HTTP (Internet), Windows | 4 Comments »

4 Responses to “ASP.NET GridView All-In-One Quick Reference”

  1. สล็อตวอเลท ไม่มีขั้นต่ำ Says:
    May 1st, 2022 at 19:27

    … [Trackback]

    […] Find More Info here to that Topic: […]

  2. buy benelli guns Says:
    May 5th, 2022 at 10:25

    … [Trackback]

    […] Read More on that Topic: […]

  3. san jose del cabo real estate Says:
    June 3rd, 2022 at 11:53

    … [Trackback]

    […] There you can find 46406 more Information to that Topic: […]

  4. sbo Says:
    August 4th, 2022 at 21:52

    … [Trackback]

    […] Read More here to that Topic: […]