Solved

ASP.NET Dynamic Column Binding Problem accessing coulmns on Update

Posted on 2004-08-08
6
1,475 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
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

840 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