How to copy gridview content to a data table on postback - asp.net

My project has a GridView to display some information. That GridView has some OnRowDataBound processing to massage the data. What I'm trying to do is copy the resulting GridView into a DataTable so I can generate a CSV file. The CSV is generated when the user clicks a button. So the GridView is on the screen and populated and a PostBack occurs. The GridView is not being re-bound on PostBack. What is the recommended way to do this? Here is the code I'm trying currently but I just end up with the headings and blank rows. Debugging confirms that row.Cells[i].Text is empty even though the heading is correct and there is the same number of rows as my GridView contained.
DataTable dataTable = new DataTable("export");
foreach (DataControlField column in myGV.Columns)
{
dataTable.Columns.Add(new DataColumn { ColumnName = column.HeaderText });
}
foreach (GridViewRow row in myGV.Rows)
{
DataRow dataRow = dataTable.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dataRow[myGV.Columns[i].HeaderText] = row.Cells[i].Text;
}
}

You need to work with the data object you're binding to the GridView, not the gridview. There is no hook to the data in the gridview after binding.

Related

Rows added to gridview don't persist when save event is triggered

I have a gridview on my webpage that can have rows added dynamically. There is a for loop that adds the rows like this:
protected void AddNewJob(object sender, EventArgs e)
{
for(int i = 0; i < Convert.ToInt32(newJobCount.Text);i++)
{
TableRow tr = new TableRow();
tr.Cells.Add(ServicesDDL("-- Select Service Type --"));
tr.Cells.Add(JobsDDL("-- Select Job Type --"));
tr.Cells.Add(TextBoxCell());
tr.Cells.Add(TextBoxCell());
tr.Cells.Add(TextBoxCell());
assetTable.Rows.Add(tr);
}
}
After the rows are added and changed from their default values the rows are looped through and data is saved to the database. I'm having problems getting the rows added to the gridview to persist and exist on the gridview when the page's save event is triggered. That code looks like this:
foreach (TableRow row in assetTable.Rows)
{
if (isFirst)
{
isFirst = false;
continue;
}
DropDownList service = (DropDownList)row.Cells[0].Controls[0];
string assetText = service.SelectedItem.Value;
DropDownList jobDescription = (DropDownList)row.Cells[1].Controls[0];
string serialText = jobDescription.SelectedItem.Value;
TextBox equipmentCount = (TextBox)row.Cells[2].Controls[0];
string leaseText = equipmentCount.Text;
TextBox jobSize = (TextBox)row.Cells[3].Controls[0];
string originText = jobSize.Text;
TextBox serialNo = (TextBox)row.Cells[4].Controls[0];
string deliveryText = serialNo.Text;
string oNo = orderNo.Text;
if (assetText != "0" && serialText != "0")
{
APICallClass.Job j = new APICallClass.Job();
j.JobTypeID = Convert.ToInt32(serialText);
j.serviceID = Convert.ToInt32(assetText);
j.equipment = leaseText;
j.jobSize = originText;
j.serialNumbers = deliveryText;
j.orderID = Convert.ToInt32(global.GlobalID);
APICallClass.API.AddJob(j, Session["Variable"].ToString());
}
}
When the code pasted above runs, it only sees the rows that are pulled in from the database. I think my problem could be fixed by calling something like .databind() somewhere that I'm not, but I've tried a few places and they have not fixed the problem.
Thanks in advance for any help, and helping me become a more robust ASP.NET developer.
When a GridView is DataBind()-ed, the contents of the GridView are "rebuilt" based on the the GridView's DataSource. If you need the new row to stay in the GridView, either do not call DataBind() after the new row is added, or ensure that the contents of your new row are in the GridView's DataSource before future calls to DataBind().
In a page I wrote once I had a similar situation and did the latter. The data for the initial rows was pulled from the database on the first page load and persisted in ViewState. As the user added, removed, and reordered rows in the GridView, the page just changed the data in ViewState and re-DataBind()ed the GridView.

how to dynamically add rows to a GridView through a DataTable without affecting any table?

I have to show a gridview in my page which doesn't concerns any table to be bound with it. Still it should store one Tax detail per row, as entered by user. Following is the image which will clarify what problem I'm facing.
The gridview shown above should not show any records at first except the footer template of two textboxes and an Add New Record Button, when you are upto add any record.
Once clicked on Add New Record button it should show a row without action column.
(I'm having quite a hard time here)Once clicked on Add/Insert Button(separate from the gridview) store the entered record somehow.
Then I have to show the record in Another concrete GridView with Edit Button.
Once I click on edit button, control should return to my dynamic gridview page. Here, my dynamic gridview will show previously entered record with action column containing a delete button.
Can you Help Me? I don't want help with the code. Just point me in the right direction(s), please.
You should try this.
private DataTable AddEmptyRow()
{
DataTable originalDataTable = GetItems();
DataTable newDataTable = originalDataTable.Clone();
string category = originalDataTable.Rows[0][2].ToString();
foreach (DataRow dRow in originalDataTable.Rows)
{
if (category != dRow[2].ToString())
{
DataRow newDataRow = newDataTable.NewRow();
newDataTable.Rows.Add(newDataRow);
category = dRow[2].ToString();
}
newDataTable.ImportRow(dRow);
}
return newDataTable;
}
You can add row by using DataRow newDataRow = newDataTable.NewRow();.

auto update table in asp.net

I have a problem. I was trying to make a table on a website. Everytime the user add a record it would display on the website. The user can add many more record on the table. My question is how do i make the table display the record automatically without saving the data into a database and retreiving it to dispaly on the the website table?
You can take benefit of gridview, datatable and viewstate.
Initially you can create a datatable and bind it in gridview
Also keep the datatable in the viewstate
Next time when user add some data add a new row in data-table
Update the viewstate data.
And again Bind the gridview.
Edit 1
Adding data to datatable
DataTable dt=new DataTable();
dt.column.Add("Name",typeof(string));
dt.column.Add("Age",typeof(int));
DataRow dr=dt.NewRow();
dr["Name"]="Mohammad"; // or dr[0]="Mohammad";
dr["Age"]=24; // or dr[1]=24;
dt.add.rows(dr);
dr=dt.NewRow();
dr["Name"]="Shahnawaz"; // or dr[0]="Shahnawaz";
dr["Age"]=24; // or dr[1]=24;
dt.add.rows(dr);
GridView1.DataSource=dt;
GridView1.DataBind();
store your datatable in view state
ViewState["dataTable"] = dt;
Now suppose you have text boxes t1 and t2
Datatable dt=ViewState["dataTable"] as DataTable;
dr=dt.NewRow();
dr["Name"]=t1.text; // or dr[0]="Shahnawaz";
dr["Age"]=t2.text; // or dr[1]=24;
dt.add.rows(dr);
Bind it to gridview again
GridView1.DataSource=dt;
GridView1.DataBind();
and keep the datatable in the view state
ViewState["dataTable"] = dt;

ASP .Net with C#(want to disable edit button of the gridview control after updating record only once)

Hello Please anyone help me for,
I want to make a program through which gridview edit command button disable once i update the record.
I have Drop-downlist control and through selection of which gridview display data. While after updating a row in gridview i have error like that "Argument Exception was handled by user code and as Flag is neither a DataColumn nor a DataRelation for table DefaultView."
in .cs file i written in the gridview1_rowdatabound event as
switch (e.Row.RowType)
{
case DataControlRowType.DataRow:
DataRowView myDataRowView = (DataRowView)e.Row.DataItem;
if (Convert.ToInt32(myDataRowView["Flag"]) > 0)
{
LinkButton EditLink = e.Row.FindControl("LinkEdit") as LinkButton;
if (EditLink != null)
{
EditLink.Visible = false;
//EditLink.Enabled = false;
}
}
break;
}
Flag is the my column value in database. After updating row in gridview its value becomes change and depends on them i can disable edit link for that perticular row of gridview. But i receive above error.
You must include your column Flag in your query , in order to find your column in your DataTable.
Add Flag column in your SelectCommand
Select Flag .... From YourTable
Nota : Your GridView control don't know your Table in DataBase, but know your DataTable, who is set in DataSource

Getting data from GridView on Button_Click

My problem is:
I have a GridView, which is bound to list of declared DTO objects with column of CheckBoxes. Also, I have a "Save" button on the page. My mission concludes in getting all rows, where CheckBox is checked and get the containing data. Unfortunately, row.DataItem = null on Button1_Click, because, I'm using if(!IsPostBack) gw.DataBind() statement (otherwise, I can't get CheckBox status). Could you give me the best practice for solving my problem?
Thank you in advance!
If you do if(!IsPostBack) --> gw.DataBind(), that will reinitialize your GridView and the checkboxes will be set to unchecked again.
In your case, in Button1_Click event, you can loop through each DataRow on your GridView and find the row which has it's checkbox checked and get all the selected row data.
foreach (GridViewRow gvRow in gw.Rows) {
// Find your checkbox
CheckBox chkBox = (CheckBox)gvRow.FindControl("checkBox");
if (chkBox.Checked) {
// Get your values
string value1 = gvRow.Cells[1].Text;
string value2 = gvRow.Cells[2].Text;
// etc...
}
}

Resources