Solved

ASP.NET Dynamic Column Binding Problem accessing coulmns on Update

Posted on 2004-08-08
6
1,477 Views
Last Modified: 2006-11-17
Hi,

I'm binding a crosstab query to a datagrid.  As a result the columns can vary in name and number, so I am dynamically create the columns at runtime.   On update I need to get the column name dynamically as it is used in the sql update.

The markup for the datagrid looks this:

<asp:datagrid id="dgTimes"
                        OnEditCommand="dgTimes_Edit" OnUpdateCommand="dgTimes_Update" OnCancelCommand="dgTimes_Cancel"
                        Runat="server"  AutoGenerateColumns="False">
                        <Columns>
                              <asp:EditCommandColumn EditText="Edit" HeaderText="Function" CancelText="Cancel" UpdateText="Update"></asp:EditCommandColumn>
                        </Columns>
                  </asp:datagrid>


In my Page_Load I call up BindGrid:

private void Page_Load(object sender, System.EventArgs e)
            {
                  if (!IsPostBack)
                  {
                        BindGrid();
                  }
            }

my BindGrid:
 - executes a stored proc to return the cross tab (between a range of dates) as a dataset
- dynamically defines BoundColumns using the dataset ColumnNames and adds them to the datagrid
- binds the dataset to the datagrid

It looks like this:

protected void BindGrid()
            {
                        // execute a stored proc to return the cross tab (between a range of dates) as a dataset
                  SqlParameter[] myParamArray = new SqlParameter[2];
                  myParamArray[0] = new SqlParameter("@startDate", "2004/01/01");
                  myParamArray[1] = new SqlParameter("@endDate", "2004/05/12");

                  DataSet ds= SqlHelper.ExecuteDataset(ConfigurationSettings.AppSettings["dbConn"].ToString(),CommandType.StoredProcedure, "sp_GetHours" ,myParamArray);

                        //dynamically define BoundColumns using the dataset ColumnNames and adds them to the
                  int numCols = ds.Tables[0].Columns.Count;
                  for (int i=0; i<numCols;i++)
                  {
                        DataColumn dc = ds.Tables[0].Columns[i];
                        
                        BoundColumn col = new BoundColumn();
                        col.HeaderText=dc.ColumnName;
                        col.DataField=dc.ColumnName;
                        
                        dgTimes.Columns.Add(col);
                  }
                  
                        //bind the dataset to the datagrid
                  dgTimes.DataSource=ds.Tables[0].DefaultView;
                  dgTimes.DataBind();
                  ds.Dispose();
            }

So far so good!

However when the update handler is fired it cannot see any of the columns in the grid apart from the EditCommandColumn.

protected void dgTimes_Update(Object sender, DataGridCommandEventArgs e)
            {
                  int numCols = e.Item.Cells.Count;
                  Response.Write ("numCols: " + numCols);
                 }

numCols comes out as 1.

What I want to do is loop through the cells on the edit row:

for (int i=0; i<numCols; i++)
                  {
                        if (e.Item.Cells[i].Controls[0] is TextBox)
                        {
                                  String colname = dgTimes.Columns[i].HeaderText.ToString();
                                          String datainput= e.Item.Cells[i].Text;
                                          //sql to insert into database to go here
                        }
                  }

but as I'm getting numCols = 1 I can't do this

Can anyone help???
0
Comment
Question by:bertybasset
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 21

Accepted Solution

by:
tovvenki earned 400 total points
ID: 11749848
HI,
since you are creating the columns dynamically you need to create it in page load so that each time the page posts back it will have access to the columns.
try this

DataSet ds;
private void Page_Load(object sender, System.EventArgs e)
{
              // execute a stored proc to return the cross tab (between a range of dates) as a dataset
               SqlParameter[] myParamArray = new SqlParameter[2];
               myParamArray[0] = new SqlParameter("@startDate", "2004/01/01");
               myParamArray[1] = new SqlParameter("@endDate", "2004/05/12");

               DataSet ds= SqlHelper.ExecuteDataset(ConfigurationSettings.AppSettings["dbConn"].ToString(),CommandType.StoredProcedure, "sp_GetHours" ,myParamArray);

                        //dynamically define BoundColumns using the dataset ColumnNames and adds them to the
               int numCols = ds.Tables[0].Columns.Count;
               for (int i=0; i<numCols;i++)
               {
                    DataColumn dc = ds.Tables[0].Columns[i];
                   
                    BoundColumn col = new BoundColumn();
                    col.HeaderText=dc.ColumnName;
                    col.DataField=dc.ColumnName;
                   
                    dgTimes.Columns.Add(col);
               }

               if (!IsPostBack)
               {
                    BindGrid();
               }
          }

protected void BindGrid()
          {
                        //bind the dataset to the datagrid
               dgTimes.DataSource=ds.Tables[0].DefaultView;
               dgTimes.DataBind();
          }

Hope that this helps you

Regards,
venki
0
 
LVL 4

Expert Comment

by:rohanpandya
ID: 11749939
Hi

   fill your datagrid into the page load event and do following. And also when update command is fired there is textboes in the datagrid so do following

     Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim connectionString As String = "Persist Security Info=False;Server=localhost;database=OnlineRecruitment;uid=sa;pwd=sa;"
            objConnection = New SqlConnection(connectionString)
            objCommand = New SqlCommand
            objCommand.CommandText = "Select * from tblUserProfile"
            objCommand.Connection = objConnection
            objDataAdapter = New SqlDataAdapter
            objDataset = New DataSet
            objDataAdapter.SelectCommand = objCommand
            objConnection.Open()
            objDataAdapter.Fill(objDataset, "Test")
            objConnection.Close()
            dgTest.DataSource = objDataset.Tables(0).DefaultView
            dgTest.DataBind()
      End Sub
      Private Sub doEdit(ByVal sender As Object, ByVal e As DataGridCommandEventArgs) Handles dgTest.EditCommand
            dgTest.EditItemIndex = e.Item.ItemIndex
            dgTest.DataBind()
      End Sub
      Private Sub doInsert(ByVal sender As Object, ByVal e As DataGridCommandEventArgs) Handles dgTest.UpdateCommand
            dgTest.SelectedIndex = e.Item.ItemIndex
            Dim txtTest As TextBox = e.Item.Cells(1).Controls(0)
            Dim test As String = txtTest.Text
            Response.Write(txtTest.Text)
      End Sub

       
0
 

Author Comment

by:bertybasset
ID: 11750853
tovvenki and rohanpandya,

thanks for you responses.

Tovennki hit the nail on the head - I've added the dynamic column building to the page load.  When I did this I could then access the datagrid columns collection.  The only problem then was that I couldn't access the Cells collection of the Selected Row.  It works now that I bind the grid each time the page loads (ie got rid of the (!PostBack) condition).  I'm guessing that as I'm creating the datagrid dynamically, it could in theory vary between page loads, and thus I have to rebind on each load (????).

My full code is:

DataSet ds;
            private void Page_Load(object sender, System.EventArgs e)
            {
                  // execute a stored proc to return the cross tab (between a range of dates) as a dataset
                  SqlParameter[] myParamArray = new SqlParameter[2];
                  myParamArray[0] = new SqlParameter("@startDate", "2004/01/01");
                  myParamArray[1] = new SqlParameter("@endDate", "2004/05/12");

                  ds= SqlHelper.ExecuteDataset(ConfigurationSettings.AppSettings["dbConn"].ToString(),CommandType.StoredProcedure, "sp_GetHours" ,myParamArray);

                  //dynamically define BoundColumns using the dataset ColumnNames and adds them to the
                  int numCols = ds.Tables[0].Columns.Count;
                  for (int i=0; i<numCols;i++)
                  {
                        DataColumn dc = ds.Tables[0].Columns[i];
                        if (dc.ColumnName.IndexOf("fk")==-1)
                        {
                              BoundColumn col = new BoundColumn();
                              col.HeaderText=dc.ColumnName;
                              col.DataField=dc.ColumnName;
                   
                              dgTimes.Columns.Add(col);
                        }
                  }

                  BindGrid();
                  
            }

            protected void BindGrid()
            {  
                  //bind the dataset to the datagrid
                  dgTimes.DataSource=ds.Tables[0].DefaultView;
                  dgTimes.DataBind();
                  ds.Dispose();
            }


            protected void dgTimes_Edit(Object sender, DataGridCommandEventArgs e)
            {
                  dgTimes.EditItemIndex = (int) e.Item.ItemIndex;
                  BindGrid();
            }

            protected void dgTimes_Cancel(Object sender, DataGridCommandEventArgs e)
            {
                  dgTimes.EditItemIndex = -1;
                  BindGrid();
            }

            protected void dgTimes_Update(Object sender, DataGridCommandEventArgs e)
            {
                  int numCols = e.Item.Cells.Count;

                  for (int i=0; i<numCols; i++)
                  {
                        if (e.Item.Cells[i].Controls[0] is TextBox)
                        {
                              String colname = dgTimes.Columns[i].HeaderText.ToString();
                              String dataValue = ((TextBox) e.Item.Cells[i].Controls[0]).Text;
                              Response.Write ("colname " + colname + "<BR>");
                              Response.Write ("dataValue " + dataValue + "<BR>");
                        }            
                  }

                  dgTimes.EditItemIndex = -1;
                  BindGrid();
            }
0
 

Author Comment

by:bertybasset
ID: 11750865
btw you'll see that I've put a condition in it so that it does not render any of the foreign keys that are in the dataset - these are all identified by "fk":

  if (dc.ColumnName.IndexOf("fk")==-1)
                    {
                     //create column
                     }
0
 
LVL 15

Expert Comment

by:praneetha
ID: 12964208
hey if u bind on each page_load...

when u edit some value after clicking "edit" button and hit "update"...it goes to page_load and again over writes the changed values with the old values...so i don't think it updates...did u try that
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …

691 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