Geeks With Blogs

@rockstarcoder
  • rockstarcoder #Setfocus .Net Masters Program students are working on AJAX, SilverLight, Web Services and Website Security this week! about 1291 days ago

News

News


Wayne Wilkerson .Net, SQL Server and other RockStar stuff

Often we have typed datasets coming back from component methods that we want to bind to a GridView at runtime. There are multiple ways to do this. The first technique is without using an ObjectDataSource, the second one is with an ObjectDataSource. Although with either technique its not to difficult to do the bind, formatting the gridview can be a challenge.

I have a small app for a library that keeps track of a library’s membership, books checked out, etc. I have  a business component that has a method which returns information about a member and another method that returns the books currently checked out by a member. This is returned in a typed dataset

My sample form looks like this.

image

 

Technique 1: Without an ObjectDataSource

The user of the page can enter a member number in the textbox and click the button. In the button click event handler the binding and formatting takes place.

protected void Button1_Click(object sender, EventArgs e)
    {
        //get a instance of business layer class
        JL.LibraryBusiness.BusinessLayer bl = new JL.LibraryBusiness.BusinessLayer();
        //get page data (non grid) by calling method
        JL.LibraryEntities.Member mymember= bl.GetMember(short.Parse(TextBox1.Text));
        TextBox2.Text = mymember.LastName;
        //get grid data by calling method and returning typed dataset
        JL.LibraryEntities.ItemsDataSet myitems= bl.GetMemberItemsOnLoan(short.Parse(TextBox1.Text));
        GridView1.Columns.Clear();
        // set the datsource of the grid
        GridView1.DataSource = myitems;
        // sets some props of the grid
        GridView1.Attributes.Add("style", "table-layout:fixed");
        //we will add columns for more control - so dont generate them 
        GridView1.AutoGenerateColumns = false;
        // add a select button
        GridView1.AutoGenerateSelectButton=true;
        //ISBNColumn
        BoundField isbn = new BoundField();
        isbn.DataField = myitems.Items.ISBNColumn.ColumnName;
        isbn.HeaderText = "ISBN";
        isbn.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        GridView1.Columns.Add(isbn);
        //CopyNumberColumn
        BoundField copyno = new BoundField();
        copyno.DataField = myitems.Items.CopyNumberColumn.ColumnName;
        copyno.HeaderText = "Copy Number";
        copyno.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        GridView1.Columns.Add(copyno);
        //TitleColumn
        BoundField title = new BoundField();
        title.DataField = myitems.Items.TitleColumn.ColumnName;
        title.HeaderText = "Title";
        GridView1.Columns.Add(title);
        //CheckoutDateColumn
        BoundField outdate = new BoundField();
        outdate.DataField = myitems.Items.CheckoutDateColumn.ColumnName;
        outdate.HeaderText = "Out Date";
        outdate.DataFormatString = "{0:MMM-dd-yyyy}"; 
        GridView1.Columns.Add(outdate);
        //DueDateColumn
        BoundField duedate = new BoundField();
        duedate.DataField = myitems.Items.DueDateColumn.ColumnName;
        duedate.HeaderText = "due date";
        duedate.DataFormatString = "{0:MMM-dd-yyyy}"; 
        GridView1.Columns.Add(duedate);
        // Bind the Grid   
        GridView1.DataBind();        
    }

 The above code adds a select button to the grid. To capture row info when the select button is clicked you can use the SelectedIndexChanged event handler.

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    //to get the row that was selected in the grid
    //cell 0 is the button
    Label1.Text = "You have selected isbn " + GridView1.SelectedRow.Cells[1].Text +
        " and copy number " + GridView1.SelectedRow.Cells[2].Text;
}

 Some formatting is best done while the grid is being populated with data, especially if the formatting depends on the data. The code below highlights the due date column red if the book is overdue. This uses the RowDataBound event handler. The width of cells can also be changed here.

 
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //change the width of a column
        e.Row.Cells[3].Width = 250;
 
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if ((DateTime.Parse(e.Row.Cells[5].Text)).Date < DateTime.Now.Date)
            {
                //change the backcolor of a cell if overdue
                e.Row.Cells[5].BackColor = System.Drawing.Color.Red;
            }
        }
        
    }

 

Technique 2: With an ObjectDatasource

 Drag an ObjectDataSource onto the page

image

Use the ObjectDataSource’s smart tag to configure.

image

 A wizard will start. Choose your business layer component.

image

 

Choose the same business component method that you called from the button click in technique 1.

image

 

Choose the field on the form to pass into that method. In this example it is Textbox1.

image 

Click Finish. The default formatted grid is displayed.

image

 The next step is to format each column as you want. Click the GridView’s smart tag and choose Edit Columns.

image

Remove columns you don't want by highlighting them in the selected fields box and click the red X.

image

 Change column properties like header text and alignment.

image

Format dates using format strings.

image

 Set column widths by using ItemStyle

image

 

Add a Select Button

image

 

Move the Select button to the first position using the up arrow.

image

 

Click OK, now the grid is formatted as desired.

image

 

Change the Button Click to use the Select method of the ObjectDataSource. Notice there is a lot less code.

protected void Button1_Click(object sender, EventArgs e)
{
        GridView1.DataBind();        
}

 

The SelectedIndexChanged event handler is the same as technique 1.

The column sizing can be removed from RowDatabound, otherwise it is also the same.

 In both techniques the page displays with proper formatting.

image

  

That is it. Good luck with your formatting!

Technorati Tags: ,,

 

Posted on Wednesday, November 11, 2009 3:16 AM | Back to top


Comments on this post: Binding an ASP.NET GridView to a typed dataset

# re: Binding an ASP.NET GridView to a typed dataset
Requesting Gravatar...
Good survey found something useful for themselves. Thank you
Left by Hypertension symptoms on Mar 03, 2011 12:29 PM

Your comment:
 (will show your gravatar)
 


Copyright © RockStarCoder | Powered by: GeeksWithBlogs.net | Join free