Getting data from GridView on Button_Click - asp.net

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...
}
}

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();.

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

ASP.net Gridview Itemtemplate Dropdownlist

I am using C# ASP.net, and relative new to it, and need to accomplish below.
In my VS2010 web application project I have webform with a Gridview which fetches the data from a table.
In the Grid, I have Commandfiled Button (column1) and Item template with Dropdownlist (column2).
Use case is, user first selects one listitem from 3 list items (H, L and M) and then selects command button.
I am not able to figure out how to extract selected listitem from a selected row
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView2.SelectedRow;
Label4.Text = "You selected " + row.Cells[4].Text + ".";
Label5.Text = "You selected this list item from dropdownlist " + ???? ;
}
Thanks in advance.
The GridViewRow object provides the method FindControl (as do all container controls) to get access to a control in the row by its id. For example, if your DropDownList has an id of MyDropDown, you could use the following to access its selected value:
GridViewRow row = GridView2.SelectedRow;
DropDownList MyDropDown = row.FindControl("MyDropDown") as DropDownList;
string theValue = MyDropDown.SelectedValue;
// now do something with theValue
This is the recommended method for accessing all controls in your GridView. You want to avoid doing things like row.Cells[#] as much as possible, because it easily breaks when you re-arrange or add/remove columns from your GridView.

storing the value of dynamically created textbox in session

I have done a project in ASP.Net that asks to input a number in textbox. After typing a number in it and click a button it generates the number of textbox according to the value given in the textbox. Like if I type 5 in the textbox it dynamically generates 5 textboxes below.
I want all the value of dynamically created textbox(more than one textbox) to be stored in session and pass to next page through session after clicking another button. But i could not do that.
How can i solve this problem.
Anyone can help me.
Thanks
You could create an array with the values and store that in the session. Code below is untested, but should give you an idea.
string[] arrayTextboxes = new string[numberOfTextboxes];
int index = 0;
foreach (Control ctrl in Page.Controls)
{
if (ctrl is TextBox)
{
arrayTextboxes[index] = ((Textbox)ctrl).Text;
index++;
}
}
Session["tbValues"] = arrayTextboxes;

Resources