Solved

Value of cell in gridview is empty (using RowDataBound event)

Posted on 2011-02-23
3
5,860 Views
Last Modified: 2012-05-11
Hi
I would like to retrieve the value of a cell in  my gridview, but all the text values are always empty!

Im using the following code:

But always the line of "e.Row.Cells[y].Text" returns an empty string... what im doing wrong?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        switch (e.Row.RowType)
        {
            case DataControlRowType.Header:
                
                columnCount = e.Row.Cells.Count;
                for (int x = 0; x < columnCount; x++)
                {
                    dtData.Columns.Add(e.Row.Cells[x].Text);
                }
                break;

            case DataControlRowType.DataRow:

                DataRow drItem = dtData.NewRow();
                for (int y = 0; y < columnCount; y++)
                {
                    drItem[y] = e.Row.Cells[y].Text;
                }
                dtData.Rows.Add(drItem);
                break;

            default:
                dsData.Tables.Add(dtData);
                Session["gv"] = dsData;
                break;

        }
    }

Open in new window

0
Comment
Question by:Veljean
  • 2
3 Comments
 
LVL 20

Expert Comment

by:Daniel Van Der Werken
ID: 34964817
The event RowDataBound is where you grab the data from a dataset presented in the ASPX page and fill the gridview with that data.  Therefore, I would expect something like this:

-- get the Data passed in via the event arg e as e.Row.DataItem cast appropriately.
-- set the gridview display cell using e.Row.Cells to take in the value you get from e.Row.DataItem.

More or less...  There are plenty of examples how to do this specifically on the web.

Therefore, on the event, RowDataBound, your initial values for the cells in the gridview are indeed string.Empty or null as you fill the gridview here.  You don't retrieve data from it.

Where you get the data is on the new event you'd set up in the RowDataBound event.

Here's what I'd do for a very simple datasource object where the e.Row.DataItem is actually just a string value:

In my aspx I have the ObjectDataSource setup like this.  Note this could be a SQLDataSoruce, but I used an Object because I actually created bogus data for a prototype I was making:

      <asp:ObjectDataSource ID="_prvODSCompanies"
                            runat="server"
                            SelectMethod="_pubGetCompanyNames"
                            TypeName="Namespace.DummyFilesClass"  >
      </asp:ObjectDataSource>

and my gridview is this:

         <asp:GridView ID="_prvGridViewCompanies"
                       runat="server"
                       AutoGenerateColumns="false"
                       CssClass="gvgrid"
                       Width="250"
                       DataSourceID="_prvODSCompanies">
            <Columns>
               <asp:TemplateField HeaderText="Select" HeaderStyle-ForeColor="Black">
                  <ItemTemplate></ItemTemplate>
               </asp:TemplateField>            
               <asp:TemplateField HeaderText="Delete" HeaderStyle-ForeColor="Black">
                  <ItemTemplate></ItemTemplate>
               </asp:TemplateField>            
               <asp:TemplateField HeaderText="Edit" HeaderStyle-ForeColor="Black">
                  <ItemTemplate></ItemTemplate>
               </asp:TemplateField>            
               <asp:TemplateField HeaderText="Company Name" HeaderStyle-ForeColor="Black">
                  <ItemTemplate></ItemTemplate>
               </asp:TemplateField>
            </Columns>
         </asp:GridView>

Note that I set this up such that I have four"empty" columns with headers.  I don't want the grid view to automatically fill these in for me because I'm going to do that myself in the RowDataBound event.

In the code behind I do this:

        void _prvGridViewCompanies_RowDataBound( object sender, GridViewRowEventArgs e )
        {
            if ( e.Row.RowType == DataControlRowType.DataRow )
            {
                CheckBox cb = new CheckBox();
                e.Row.Cells[ 0 ].Controls.Add( cb );   // matches the "select" column

                ImageButton delIconButton = new ImageButton();
                delIconButton.ImageUrl = "~/images/delete_redx_small.png";
                e.Row.Cells[ 1 ].Controls.Add( delIconButton );  // matches the delete column

                ImageButton edIconButton = new ImageButton();
                edIconButton.ImageUrl = "~/images/pencil_image.png";
                e.Row.Cells[ 2 ].Controls.Add( edIconButton );  // matches the edit column

                LinkButton linkButton = new LinkButton();
                linkButton.Text = e.Row.DataItem.ToString();  // this is simple because my datasource is a List<string>
                linkButton.Click += new EventHandler( linkButton_Click );
                e.Row.Cells[ 3 ].Controls.Add( linkButton );  // matches the "company name" column
            }
        }

I could have added events for all of the buttons I made, but I didn't because I was lazy and just setting this up for demo purposes for myself only, but note that I did add a new event handler for the link button I created here.

All I have to do now is set up the event:

        void linkButton_Click( object sender, EventArgs e )
        {
            LinkButton lb = ( LinkButton )sender;
            string lbText = lb.Text;
        }

Actually, clicking on the link doesn't do anything except for set lbText to the value I clicked on in the gridview, but that's good enough for me if I set my breakpoint there and look at the value to confirm I got what I expected.

I hope this helps.




0
 
LVL 1

Author Comment

by:Veljean
ID: 34964934
Thanks Dan7el, you put me in the right direction...
 Using a expression like this:

 string strColumn = DataBinder.Eval(e.Row.DataItem,"Column1").ToString();

I was able to read the value of the cell I wanted.

Only one more tip please, since I have more than 45 columns is tedious for me to reference one by one, it exists a method to dynamically get the name of the columns from e.Row.DataItem?

something like this?

 
for (int y = 0; y < columnCount; y++)
                {
                  
                    string strColumna = e.Row.DataItem.ColumnName[y]; //Obviously this is incorrect
                    drItem[y] = DataBinder.Eval(e.Row.DataItem, strColumna).ToString();



                }

Open in new window

0
 
LVL 20

Accepted Solution

by:
Daniel Van Der Werken earned 500 total points
ID: 34970513
               DataRowView dv = e.Row.DataItem as DataRowView;
                DataRow dr = dv.Row;
                string firstName = dr[ "FirstName" ].ToString();
                string lastName = dr[ "LastName" ].ToString();
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
ADO.NET ENTITY DATA MODEL 3 30
Name space syntax error 12 41
IIS Express Working in one Visual Studio Solution, but not in another. Why? 2 15
how to read json value 2 30
Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
As a trusted technology advisor to your customers you are likely getting the daily question of, ‘should I put this in the cloud?’ As customer demands for cloud services increases, companies will see a shift from traditional buying patterns to new…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now