I have a GridView that has 10 columns populated by CheckBoxes. But instead of using FindControl() is there a way to get the CheckBox.Checked value by using a loop?
Current Code:
if (e.CommandName == "updaterow")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
// TableCell BranchCode = selectedRow.Cells[0];
CheckBox cb101 = (CheckBox)selectedRow.FindControl("cb101");
CheckBox cb102 = (CheckBox)selectedRow.FindControl("cb102");
//...and so on
}
ASPX CODE:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="101">
<ItemTemplate>
<asp:CheckBox runat="server" id="cb101" AutoPostBack="false" Checked='<%# Eval("101").ToString()=="1" ? true : false %>' Enabled='<%#(String.IsNullOrEmpty(Eval("101").ToString()) ? false: true) %>'/>
</ItemTemplate>
</asp:TemplateField>
....and so on
<asp:ButtonField ButtonType="Button" CommandName="updaterow" Text="Update"/>
</Columns>
</asp:GridView>
Try this,
Using foreach Loop:
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
if (chk != null && chk.Checked)
{
// ...
}
}
Use it in OnRowCommand event and get checked CheckBox value.
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];
For run all lines of GridView don't use for loop, use foreach loop like:
foreach (GridViewRow row in yourGridName.Rows) //Running all lines of grid
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
//if checked do something
}
}
}
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkbox = (CheckBox)row.FindControl("CheckBox1");
if (chkbox.Checked == true)
{
// Your Code
}
}
If you want a method other than findcontrol try the following:
GridViewRow row = Gridview1.SelectedRow;
int CustomerId = int.parse(row.Cells[0].Text);// to get the column value
CheckBox checkbox1= row.Cells[0].Controls[0] as CheckBox; // you can access the controls like this
foreach (DataRow row in DataRow row in GridView1.Rows)
{
foreach (DataColumn c in GridView1.Columns)
bool ckbVal = (bool)(row[c.ColumnName]);
}
Blockquote
foreach (GridViewRow row in tempGrid.Rows)
{
dt.Rows.Add();
for (int i = 0; i < row.Controls.Count; i++)
{
Control control = row.Controls[i];
if (control.Controls.Count==1)
{
CheckBox chk = row.Cells[i].Controls[0] as CheckBox;
if (chk != null && chk.Checked)
{
dt.Rows[dt.Rows.Count - 1][i] = "True";
}
else
dt.Rows[dt.Rows.Count - 1][i] = "False";
}
else
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text.Replace(" ", "");
}
}
You want an independent for loop for all the rows in grid view, then refer the below link
http://nikhilsreeni.wordpress.com/asp-net/checkbox/
Select all checkbox in Gridview
CheckBox cb = default(CheckBox);
for (int i = 0; i <= grdforumcomments.Rows.Count – 1; i++)
{
cb = (CheckBox)grdforumcomments.Rows[i].Cells[0].FindControl(“cbSel”);
cb.Checked = ((CheckBox)sender).Checked;
}
Select checked rows to a dataset; For gridview multiple edit
CheckBox cb = default(CheckBox);
foreach (GridViewRow row in grdforumcomments.Rows)
{
cb = (CheckBox)row.FindControl("cbsel");
if (cb.Checked)
{
drArticleCommentsUpdates = dtArticleCommentsUpdates.NewRow();
drArticleCommentsUpdates["Id"] = dgItem.Cells[0].Text;
drArticleCommentsUpdates["Date"] = System.DateTime.Now;dtArticleCommentsUpdates.Rows.Add(drArticleCommentsUpdates);
}
}
Related
I'm using checkbox to remove a row from data table; when I check one of the boxes; the row is removed. But if i check all the boxes; it gives this error message There is no row at position 1.. And if I go back to checking one box no row is removed.
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = row.FindControl("chkInvoice") as CheckBox;
if (chk != null && chk.Checked)
{
dt.Rows.RemoveAt(row.RowIndex);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
If you use foreach, you will be modifying the rows while iterating them. So do a reverse loop and remove based on index.
for(int i = GridView1.Rows.Count - 1; i >= 0; i--)
{
var row = GridView1.Rows[i];
CheckBox chk = row.FindControl("chkInvoice") as CheckBox;
if (chk != null && chk.Checked)
{
dt.Rows.RemoveAt(i);
}
}
Footer is set to visible and I can see it's being created. However when total (table sums) are passed over to it, there's error indicating GridView2.FooterRow is null...
totTable refers to a DataTable carrying totals.
aspx:
ShowHeader="true" ShowFooter="true" FooterStyle-CssClass="FooterStyle"
cs:
DataRow dr = totTable.Rows[0];
foreach (DataControlField col in GridView2.Columns)
{
foreach (DataColumn dc in totTable.Columns)
{
int i = GridView2.Columns.IndexOf(col);
GridView2.FooterRow.Cells[i].Text = dr[i].ToString();
}
}
What's the root cause behind this?
use following code after binding gridview:
public void CountGrandTotal()
{
int sum = 0;
for (int i = 0; i <grdproduct.Rows.Count ; i++)
{
Label lblprice = (Label)grdproduct.Rows[i].FindControl("Label5");
sum += int.Parse(lblprice.Text);
}
Label lblgtotal = (Label)grdproduct.FooterRow.FindControl("Label7");
lblgtotal.Text = sum.ToString();
Add the footer on the OnLoad method of the GridView.
<asp:GridView ID="Gv"
runat="server"
ShowFooter="true"
OnLoad="Gv_Load">
I am having some problem for getting the text from textbox in a row which the checkbox was marked check in gridview. When button on click, it supposed to get the checked row index for prodID and the quantity which is the text from textbox:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
string quantity = "" , prodID = "";
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//Get the productID which set as DataKeyNames for selected row index
prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
quantity = tbQuantity.Text;
}
tempList.Add(prodID);
}
}
}
}
for (int i = 0; i < tempList.Count; i++)
{
//Testing
lblTest.Text += tempList[i] + " " + quantity;
}
}
Let's say I got prodID 1 with 50 units, prodID 2 with 77 units, prodID 3 with 90 units. When I loop thru the tempList, this is the result which I supposed to get:
1 50units, 2 77units, 390units
However, the codes does not get the quantity from the textbox for each product independently. Here is the result which I get:
1 90units, 2 90units, 3 90units
It just simply get the quantity of last product in the list. I wonder is there any way to fix this? Thanks in advance.
Edited Portion:
foreach (string key in tempList.Keys)
{
packagesNeeded = 1;
unitQty = prodPackBLL.getUnitQtySPU(tempList[key]);
lblTest.Text += key + " " + tempList[key];
if (Convert.ToInt32(quantity) < (packagesNeeded * unitQty))
{
//Pop up message
Page.ClientScript.RegisterStartupScript(GetType(), "UserDialogScript", "alert(\"Insufficient storage\");", true);
}
}
You can use Dictionary to pair each prodID with its corresponding quantity. Try this code:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
Dictionary<string, string> tempList = new Dictionary<string, string>();
string quantity = "", prodID = "";
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//Get the productID which set as DataKeyNames for selected row index
prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
quantity = tbQuantity.Text;
}
tempList.Add(prodID, quantity);
}
}
}
}
foreach (string key in tempList.Keys)
{
packagesNeeded = 1;
unitQty = prodPackBLL.getUnitQtySPU(key);
lblTest.Text += key + " " + tempList[key];
if (Convert.ToInt32(tempList[key]) < (packagesNeeded * unitQty))
{
//Pop up message
Page.ClientScript.RegisterStartupScript(GetType(), "UserDialogScript", "alert(\"Insufficient storage\");", true);
}
}
}
Based on your examples above, tempList["1"] will produce "50", tempList["2"] will produce "77", and tempList["3"] will produce "90".
It is because you keep overriding variable "quantity" for each row you have the checkbox selected. If you want to store multiple values you need to use List<string> to store the quantities for each row where the checkbox is selected.
Something like below. Note: I haven't tested the code.
protected void lbnConfirm_Click(object sender, EventArgs e)
{
List<string> quantity = new List<string>();
prodID = "";
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//Get the productID which set as DataKeyNames for selected row index
prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
quantity.Add(tbQuantity.Text);
}
tempList.Add(prodID);
}
}
}
}
for (int i = 0; i < tempList.Count; i++)
{
//Testing
lblTest.Text += tempList[i] + " " + quantity[i];
}
}
you can do something like :
foreach (DataGridViewRow item in GV.Rows)
{
if (Convert.ToBoolean(item.Cells[0].Value) == true)
//here you get the rowcell value :
string val = item.Cells[1].Value.ToString();
//If you want to convert to a textbox :
TextBox textBox = (TextBox)item.Cells[1].Value;
}
where GV is the gridview Id
and checkbox is the 0 column and the value you might want to get is the 1 column
I have gridview with template field of dropdownlist in each row.when i select any value from dropdownlist it will change color of 3rd row below than it.But when i click on another dropdownlist it is changing the color of 3rd row below than it but the index of previous dropdownlist is not changed to 0 i.e"Select".it is still showing the value selected in last dropdown list.I just want when i click on a dropdownlist ,all other dropdownlist should be indexed to 0 i.e "Select" except one which i have clicked.
I am doing following in Selectedindexchange event of dropdownlist:
protected void GridView1_SelectedIndexChanged(object sender,EventArgs e)
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
int g1 = gvRow.RowIndex;
GridView1.Rows[g1].BackColor = Color.White;
}
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.NamingContainer;
int g = row.RowIndex + 3;
int current_row_index = row.RowIndex;
int pp = GridView1.Rows.Count;
GridView1.Rows[g].BackColor = Color.Red;
}
}
Thanks in advance.
Just use DropdownName.ClearSelection() for each of your other dropdown except the one where you are calling Selectedindexchange event.
Maybe something like this:
protected void GridView1_SelectedIndexChanged(object sender,EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.NamingContainer;
int g = row.RowIndex + 3;
int current_row_index = row.RowIndex;
foreach (GridViewRow gvRow in GridView1.Rows)
{
gvRow.BackColor = Color.White;
if (gvRow.FindControl("nameOfTheDropdown") != null && gvRow.RowIndex != current_row_index)
{
((DropDownList)gvRow.FindControl("nameOfTheDropdown")).SelectedIndex = 0;
}
}
GridView1.Rows[g].BackColor = Color.Red;
}
Regards
i am using checkbox in gridview..to get the checkbox id i am using the following code..
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)GridView1.Rows.Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = GridView1.Rows.Cells[1].Text;
idCollection.Add(strID);
}
}
}
BUT THE KEYWORD "CELLS"..do not support..i am getting an error.."System.Web.UI.WebControls.GridViewRowCollection' does not contain a definition for 'Cells' "
This is the way you have to check
foreach (GridViewRow grRow in grdACH.Rows)
{
CheckBox chkItem = (CheckBox)grRow.FindControl("checkRec");
if (chkItem.Checked)
{
strID = ((Label)grRow.FindControl("lblBankType")).Text.ToString();
}
}
That's correct; the GridViewRowCollection class does not contain either a method or a property with the name Cells. The reason that matters is that the Rows property of the GridView control returns a GridViewRowCollection object, and when you call GridView1.Rows.Cells, it is searching for a Cells property on the GridViewRowCollection object returned by the Row property.
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)GridView1.Rows[i].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = GridView1.Rows[i].Cells[1].Text;
idCollection.Add(strID);
}
}
}
foreach (GridViewRow rowitem in GridView1.Rows)
{
CheckBox chkDelete = (CheckBox)rowitem.Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = rowitem.Cells[1].Text;
idCollection.Add(strID);
}
}
}