Solved

ASP.NET Dynamic Column Binding Problem accessing coulmns on Update

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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

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…
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

813 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

14 Experts available now in Live!

Get 1:1 Help Now