I have a gridview with checkbox in my codebehind page. The functionality is that I need to select the records to be deleted using checkbox and click the delete button. I use the below code to do that.. But when I select the last row it does not get deleted. Instead it throws IndexOutOfRange/ System.FormatException ..
The error is thrown at this line
CheckBox chkb = (CheckBox)gvAll.Rows[i].Cells[0].FindControl("chk");
for (int i = 0; i < count; i++)
{
CheckBox chkb = (CheckBox)gvAll.Rows[i].Cells[0].FindControl("chk");
if (chkb.Checked == true)
{
string name = gvAll.Rows[i].Cells[3].Text;
if (!(name.Equals(System.DBNull.Value)))
{
a.delete(name);
}
}
}
It's an urgent issue. Please help..
How about a foreach?
foreach(GridViewRow row in gvAll.Rows)
{
CheckBox chkb = (CheckBox)row.Cells[0].FindControl("chk");
if (chkb.Checked == true)
{
string name = row.Cells[3].Text;
if (!(name.Equals(System.DBNull.Value)))
{
a.delete(name);
}
}
}
Related
In my asp.net application, I have used Gridview control, In which i have to add Dropdownlist at runtime for each cell.Which i am able to bind successfully.
Below is my code which inside row databound event,
foreach (GridViewRow row in gdvLocation.Rows) {
if (row.RowType == DataControlRowType.DataRow) {
for (int i = 1; i < row.Cells.Count; i++) {
var dlRouteType = new DropDownList();
dlRouteType.ID = "ddlRouteType";
dlRouteType.DataSource = GetRouteTypeList();
dlRouteType.DataTextField = "RouteType";
dlRouteType.DataValueField = "Id";
dlRouteType.DataBind();
row.Cells[i].Controls.Add(dlRouteType);
}
}
}
I have a button in my page, which has functionality to save data to database . While saving data i have to pass the value from Dropdownlist which i have added at runtime. On button click i am writing following code to get data from dropdownlist,
var ddlDropDown = (DropDownList)row.Cells[i].FindControl("ddlRouteType");
But i am getting null in ddlDropDown object. I have even added Update panel inside aspx page. Any suggessions most welcome.
Thanks in advance
Sangeetha
You have these errors in your code
RowDataBound already iterates through each rows and so all you need not write that foreach on top
You are iterating from index 1, index are zero-based. So start from zero.
The DropDownList ID must be unique, so better write something like,dlRouteType.ID = "ddlRouteType_" + i;
The code should be,
protected void gdvLocation_RowDataBound(object sender, GridViewRowEventArgs e)
{
//removed the foreach loop
var row = e.Row;
if (row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < row.Cells.Count; i++) //changed index
{
var dlRouteType = new DropDownList();
dlRouteType.ID = "ddlRouteType_" + i; //gave unique id
dlRouteType.DataSource = GetRouteTypeList();
dlRouteType.DataTextField = "RouteType";
dlRouteType.DataValueField = "Id";
dlRouteType.DataBind();
row.Cells[i].Controls.Add(dlRouteType);
}
}
}
I have a loaded DataGrid. In that DataGrid the first column is a CheckBox, and the second column is "Name". Also I have saved one field "Name" in the database . Here I want to make the CheckBox to be checked if the Name is equal to the data which I stored in the database.
Here my problem is that ,I am getting only one CheckBox to to be checked.
ex:[ If my expected result is 1st, 2nd and 3dr CheckBoxes to be checked , But I am getting only the 3rd one as checked. ]
my sample code is
foreach (GridViewRow row in GrdProduct.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label lblproduct = (Label)row.FindControl("lblProduct");
CheckBox chkSelect = (CheckBox)row.FindControl("chkSelectAll");
for (int rowIndex = 0; rowIndex < dt.Rows.Count; rowIndex++)
{
DataRow r = dt.Rows[rowIndex];
if (Convert.ToString(r["productName"]) == lblproduct.Text)
{
chkSelect.Checked = true;
}
else
{
chkSelect.Checked = false;
}
}
}
Finally I got the solution ... Simply removed the else part
else
{
chkSelect.Checked = false; }
--
thank you all...
Sorry I am blind. You are looping through the datarows and of course you most likely have only one match. In all other cases it becomes unchecked right after. Use the following:
foreach (GridViewRow row in GrdProduct.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label lblproduct = (Label)row.FindControl("lblProduct");
CheckBox chkSelect = (CheckBox)row.FindControl("chkSelectAll");
chkSelect.Checked = false;
for (int rowIndex = 0; rowIndex < dt.Rows.Count || !chkSelect.Checked; rowIndex++)
{
DataRow r = dt.Rows[rowIndex];
if (Convert.ToString(r["productName"]) == lblproduct.Text)
{
chkSelect.Checked = true;
}
}
}
Als when comparing strings I recommend http://msdn.microsoft.com/en-us/library/system.string.equals(v=vs.110).aspx
COmpared what you are going to do with the data and controls in the grid I also recommend additional validation.
I need to check wheather the radionbutton is checked Or NOT then need to have its value to a variable .
How can i loop through the radioButtonList in repeater to check that user choose True or false on button click and button is placed outside the gridview and repeater.
I tried this:
protected void btnsave_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
int tcounter = 0;
int fcounter = 0;
for (int i = 0; i < gridMainSurveyQuestion.Rows.Count; i++)
{
GridView grid = (GridView)gridMainSurveyQuestion.Rows[i].FindControl("RptQuestions");
Repeater repea = (Repeater)grid.Rows[i].FindControl("RptQuestions");
for (int j = 0; j < repea.Items.Count; j++)
{
RepeaterItem currentitem = repea.Items[j];
RadioButtonList rlist = (RadioButtonList)currentitem.FindControl("rblanswer");
if (rlist.SelectedItem.Value == "0")
{
fcounter++;
lblfalse.Text = fcounter.ToString();
}
if (rlist.SelectedItem.Value == "1")
{
tcounter++;
lbltrue.Text = tcounter.ToString();
}
}
}
}
but shows error:
Unable to cast object of type 'System.Web.UI.WebControls.Repeater' to type 'System.Web.UI.WebControls.GridView'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Unable to cast object of type 'System.Web.UI.WebControls.Repeater' to type 'System.Web.UI.WebControls.GridView'.
Source Error:
Line 89: for (int i = 0; i < gridMainSurveyQuestion.Rows.Count; i++)
Line 90: {
Line 91: GridView grid = (GridView)gridMainSurveyQuestion.Rows[i].FindControl("RptQuestions"); Line 92:
Line 93: Repeater repea = (Repeater)grid.Rows[i].FindControl("RptQuestions");
Source File: C:\Users\madiha.rahman\Desktop\PICG_SurveyModule\PICG_SurveyModule\Survey.aspx.cs Line: 91
can you correct it
You will first need to iterate through GridView Rows for finding each repeater. Then from each repeater find each radiobuttonlist, like shown below.
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvRow in gvTemp.Rows)
{
Repeater repeater = (Repeater)gvRow.FindControl("repeater1");
foreach (RepeaterItem repItem in repeater.Items)
{
RadioButtonList rbList = (RadioButtonList)repItem.FindControl("radiobuttonlist1");
foreach (ListItem item in rbList.Items)
{
if (item.Selected)
{
//code for selected items goes here...
}
else
{
//code for not selected items goes here...
}
if (item.Value == "0")
{
//code for items with value == "0" goes here...
}
if (item.Value == "1")
{
//code for items with value == "1" goes here...
}
}
}
}
}
Happy Coding...;)
EDIT : Removed the checkbox & placed radiobuttonlist as required by the questioner.
EDIT : Added inner foreach loop that iterates through each radiobutton in the radiobuttonlist, as requested by the Questioner.
Can you please help me on this, I get the check box control value as false always even when I check the control in gridview.
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox CheckBox1 = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (CheckBox1 != null)
{
if (CheckBox1.Checked)
{
query = GridView1.Rows[i].FindControl("Label1") + ",";
}
}
}
Are you databinding on Page_Load method? If yes, you must do this:
if(!IsPostBack)
{
GridView1.DataSource = YourData;
}
If you don't do this, your DataGridView will be databound even if it is a PostBack. This way no matter what you checked, the DataGridView will be repopulated from the data source for your postbacks.
Using the above code, when you do if(!IsPostBack), it will retain the checkbox's viewstate value and you get the correct Checked status.
Inside the checkbox design add the following attribute
ToolTip="<%#Container.DataItemIndex+1 %> " and then following is the code behind
for (int i = 0; i < gdview.Rows.Count; i++)
{
string labeldetail = "";
CheckBox cbox = (CheckBox)gdview.Rows[i].Cells[0].FindControl("CheckBox1");
if (cbox != null)
{
if (cbox.Checked == true)
{
int rowsNo = (Convert.ToInt16(city.ToolTip) - 1); //Convert.ToInt16(SrNo);
labeldetail = ((Label)gdview.Rows[rowsNo].FindControl("labelid")).Value;
}
I have a datagridview with one DataGridViewCheckBoxColumn and some other TextBox Columns. I want to loop through each cell and see if the checkbox is checked then do something. I am using the following looping method. Is there a better way to do??
I have used or condition because in some computers it brings .Value as Checked and in some it bring .Value as true.
foreach (DataGridViewRow row in dataGridView.Rows)
{
if ((bool)(row.Cells["Checkbox"]).Value || (CheckState)row.Cells["Checkbox"].Value == CheckState.Checked)
{
// Do something
}
}
Thanks in advance.
i think this will be faster than foreach
for (int i = 0; i < dataGridView.Rows.Count -1; i++)
{
DataGridViewRow row = dataGridView.Rows[i];
if ((bool)(row.Cells["Checkbox"]).Value
|| (CheckState)row.Cells["Checkbox"].Value == CheckState.Checked)
{
// Do something
}
}
It worked for me using following code:
foreach (DataGridViewRow row in dgv_labelprint.Rows)
{
if (value.Value == null)
{
}
else
if ((Boolean)((DataGridViewCheckBoxCell)row.Cells["CheckBox"]).FormattedValue)
{
//Come inside if the checkbox is checked
//Do something if checked
}
}
Have a look at this link DirtyCellChanged You can then keep track of which rows have been checked and do your work, rather than having to loop through the whole table.
This event is useful when dealing with checkboxes as users sometimes click check, and then don't commit the edit by clicking somewhere else.
It's worked good for me in the past.
int subId;
List<int> olist= new List<int>();
for (int i = 0; i < gvStudAttend.Rows.Count; i++)
{
bool Ischecked = Convert.ToBoolean(gvStudAttend.Rows[i].Cells["Attendance"].Value);
if (Ischecked == true)
{
subId = gvStudAttend.Rows[i].Cells["SubjectID"].Value.ToString();
olist.Add(subId );
}
}