Question about checkbox and datagridview - c#

I have datagridview with checkbox column, and the checkbox within the column can be checked or unchecked with external checkbox. It works fine while selecting all the columns and saving the data in database. But, when I unchecked the checkbox in the datagridview with external checkbox and again select the single checkbox within the datagridview, it again takes the rowindex of all the checkbox within the column.
if (chkbranches.Checked == true)
{
foreach (DataGridViewRow dr in gridviewholiday.Rows)
{
dr.Cells[0].Value = true;
}
for (int i = 0; i < gridviewholiday.Rows.Count; i++)
{
rowindex = i;
list.add(rowindex);//to put the rowindex in array list
}
}
else if (chkbranches.Checked == false)
{
foreach (DataGridViewRow dr in gridviewholiday.Rows)
{
dr.Cells[0].Value = false;
gridviewholiday.Refresh();
gridviewholiday.ClearSelection();
list.Clear();
}
}

Why do you loop twice if chkbranches is checked? Can't you add items to the list within the first foreach? And in the loop for unchecking, why do you refresh, and clear both controls each time? Probably only needed once.
And as mentioned, this isn't doing anything about single checks. If you're expecting it to, that seems to be the problem.

Not quite sure what your attempting to do, but I have something similar with a button that deletes all the checked rows. I use a template field like so for the check box:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cbSelector" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Then for the Delete button code behind I do:
protected void btnDeleteChecked_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gridOrders.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("cbSelector");
if ((null != cb) && cb.Checked)
{
uint id = Convert.ToUInt32(gridOrders.DataKeys[row.RowIndex].Value);
gInvoiceDB.DeleteInvoice(id, true);
}
}
}

Related

selecting specific control from a cell that contains multiple controls

In the last column of my asp .net GridView I have an image and a checkbox. I want to check if that checkbox is checked, for all rows. I am getting null reference exception at if cause maybe chk is null. any help?
try
{
foreach (GridViewRow row in grdSurveyDetails.Rows)
{
int index = row.Cells.Count - 1;
CheckBox chk = row.Cells[index].Controls[1] as CheckBox;
int rowIndex = row.RowIndex;
if (chk.Checked)
{
ClientScript.RegisterClientScriptBlock(typeof(Page), "alert", "<script>alert("+rowIndex+" is checked!);</script>");
}
}
}
catch (Exception)
{
throw;
}
I'm assuming that you populate the gridview via code, so that you always have an image and checkbox in that last cell. If that's the case, something that come to my mind is that you may be accessing the header row which does not have the checkbox in there.
Nonetheless, could you try doing the null check in there, something like
if (chk?.Checked)
That ? is doing a null check for you. If it's null, then do not do anything with that row.
NB: if the cell doesn't always contains image and checkbox, then use caution as you may have a checkbox in that cell which wasn't at index 1 (ie: you may consider using #Rojalin Sahoo approach to search for checkbox explicitly)
You can check all checked like this
Lets say you have
Aspx
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Then in
Code Behind
foreach (GridViewRow row in grdSurveyDetails.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
int index = row.Cells.Count - 1;
CheckBox chkRow = (row.Cells[index].FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
//do something
}
}
}
Please look at this complete example
Here

delete from gridview using checkboxs

hi gusy im trying to anderstand how delete from database using grindview with checkboxs but i dont know why deleteresults.text and DeleteResults.Visible dont work this is my code (im new in programming :) and thx for your answers
protected void Button3_Click(object sender, EventArgs e)
{
bool atLeastOneRowDeleted = false;
// Iterate through the Products.Rows property
foreach (GridViewRow row in Products.Rows)
{
// Access the CheckBox
CheckBox cb = (CheckBox)row.FindControl("selector");
if (cb != null && cb.Checked)
{
// Delete row! (Well, not really...)
atLeastOneRowDeleted = true;
// First, get the ProductID for the selected row
int id_offre = Convert.ToInt32(Products.DataKeys[row.RowIndex].Value);
// "Delete" the row
DeleteResults.Text += string.Format("This would have deleted ProductID {0}<br />", id_offre);
}
}
// Show the Label if at least one row was deleted...
DeleteResults.Visible = atLeastOneRowDeleted;
}
Have you set the DataKeyNames property on your GridView? You need to do that to use DataKeys[index]. According to MSDN, when you set the DataKeyNames property, the DataKeys object gets populated. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeys(v=vs.100).aspx. Try setting that property, read more on that on MSDN.

Inserting data to GridView using CheckBox

I have a GridView and I put checkboxes inside all its cells. I want to do the following:
if the checkbox checked by the user, this means Yes which will be stored in the database
else, if the checkbox unchecked by the user, this means No and no need to post anything to the database.
I know I need now to identify each checked checkbox and know which cell this checked checkbox is underneath it.
Any idea about how to do that? Could anyone give me the basic piece of code for doing this?
I use something similar to this:
foreach (GridViewRow row in gvYourGridView.Rows)
{
CheckBox ck = ((CheckBox)row.FindControl("YourCheckBoxName"));
if (ck.Checked)
{
//If checked is true, update database.
}
}
int counter = 0;
foreach (GridViewRow rowitem in gvYourGridView.Rows)
{
if (((CheckBox)rowitem.Cells[0].FindControl("chk")).Checked == true)//i consider that the check box is in the first column index ---> 0
{
counter++;
}
}
/////////////////////////////////////////////////////////////
if(counter == 0) //no checks
{
//show some message box to clarify that no row has been selected.
}
/////////////////////////////////////////////////////////////
if (counter == 1) //one check
{
//Do something
}
/////////////////////////////////////////////////////////////
if (counter > 1) //more than one check
{
//Do something
}
gvYourGridView.DataBind();

Is there a way to use OnMouseOver to select a radgrid row?

I am currently highlighting a row in a radgrid using OnMouseOver. I would like to know if it is possible to use OnMouseOver to select the row rather than highlight it.
Alternatively, I would like the highlighted row to remain highlighted if the radgrid loses focus, such as when a confirmation box pops up.
Thanks in advance.
According to Telerik documentation, it should be possible to select the item OnMouseOver using the following code (if you don't have any detail tables you can nix the if statement and just use the code from the else block to find the currentDataItem):
function RadGrid1_RowMouseOver(sender, eventArgs) {
var currentDataItem = null;
// clear all currently selected items before selecting new
sender.get_masterTableView().clearSelectedItems();
if (eventArgs.get_itemIndexHierarchical().indexOf(':') > 0)
{
var detailTableIndex = eventArgs.get_itemIndexHierarchical().split(':')[0];
var rowIndex = eventArgs.get_itemIndexHierarchical().split(':')[1].split('_')[1];
currentDataItem = sender.get_detailTables()[detailTableIndex].get_dataItems()[rowIndex];
}
else
{
currentDataItem = sender.get_masterTableView().get_dataItems()[eventArgs.get_itemIndexHierarchical()];
}
if (currentDataItem != null)
{
currentDataItem.set_selected(true);
}
}
The other answers here do not work with the WPF Telerik RadGridView as we don't have access to RowMouseOver event.
For a WPF Telerik RadGridView, the best approach if the grid doesn't contain UI elements is to use ChildrenOfType<> in a Linq expression with IsMouseOver.
private void myGridView_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
MyCustomClass myClass = null;
var rows = this.myGridView.ChildrenOfType<GridViewRow>().Where(r => r.IsMouseOver == true);
foreach (var row in rows)
{
if (row is GridViewNewRow) break;
GridViewRow gvr = (GridViewRow)row;
myClass = (MyCustomClass)gvr.Item;
}
// do something with myClass here if we have found a row under mouse
}
Thanks! Your solution worked great, but rows would not become unselected when mousing over another row even if AllowMultiRowSelection was set to False. The following code will select a single row in the radgrid when the mouse hovers over the row:
<script type="text/javascript">
function grdUsers_RowMouseOver(sender, eventArgs) {
var NumberItems = sender.get_masterTableView().get_dataItems().length;
for (var count = 0; count < NumberItems; count++) {
var currentDataItem = sender.get_masterTableView().get_dataItems()[count];
if (count == eventArgs.get_itemIndexHierarchical()) {
currentDataItem.set_selected(true);
}
else {
currentDataItem.set_selected(false);
}
}
}
</script>
I called the function at the following location:
<ClientSettings AllowColumnsReorder="True" ReorderColumnsOnClient="True">
<Selecting AllowRowSelect="True" />
<ClientEvents OnRowMouseOver="grdUsers_RowMouseOver" />
</ClientSettings>

How to check for an Empty Gridview

I have an ASP.NET 2.0 (C#) web app, and in it I have a gridview that gets its data from an oracle database.
I want to know how to check if the gridview is empty, and the do something.
I have already tried:
if(GridView.Rows.Count == 0)
{
// Do Something
}
but it doesn't work...
Any ideas?
Thank you.
Your code should work. But only after GridView.DataBind() has been called. Generally I don't check the GridView it's self, but the datasource of the grid view.
DataTable data = DAL.getdata();
if (data.Rows.Count == 0)
{
ShowEmptyData();
}
else
{
Grid.DataSource = dt;
Grid.DataBind();
}
This doesn't work since the GridView is data bound and is going to fetch the actual data at a later time while rendering the page. You should check this by directly querying the data binding source of the gridview (see if the actual list that's grid view bound to is empty or not).
If you just want to display something when it's empty, you should use <EmptyDataTemplate> in your markup:
<asp:GridView runat="server">
<EmptyDataTemplate>The grid is empty</EmptyDataTemplate>
</asp:GridView>
I agree with the other responses. I want to add little information, you should get rows.count after databind method :
int rowCount = GridView.Rows.Count; // returns zero
GridView.DataBind();
rowCount = GridView.Rows.Count; // returns actual row count
If you're using databinding, the the row count of the datasource not the count on the grid itself.
Its very easy: Hope it works for you.. :)
Use event of GridView DataBound: which fires after data is bound.
protected void GridView1_DataBound(object sender, EventArgs e)
{
int rowCount = GridView1.Rows.Count;
if (rowCount == 0)
{
GridView1.Visible = false;
}
else
{
GridView1.Visible = true;
}
}
First create a helper class.
public static class GridViewExtensions
{
public static IEnumerable<GridViewRow> AsEnumerable(this GridView grid)
{
foreach (GridViewRow row in grid.Rows)
{
yield return row;
}
}
public static bool IsEmpty(this GridView grid)
{
return !grid.AsEnumerable().Any(t => t.RowType == DataControlRowType.DataRow);
}
}
Then just call IsEmpty
GridView1.IsEmpty()
In case you've configured your GV to automatically fetch the data from DB, then you may add the following line as the first statement of your GV in Source mode:
<EmptyDataTemplate>No data found.</EmptyDataTemplate>
And then continue with the normal code in your GV.
Based on answers already, GridView.Rows.Count is not enough on its own, depending on the nature of your GridView, especially if it's a dynamic gv, which in most cases it is, plus you have to factor in Paginating, Headers and Footers, which alter the row count.
I use a simple method to tell me ...
//checks if a gridview has any actual rows of data (not just blank rows filled in by the Load
protected bool gvNoData(GridView gv)
{
int wsDataRow = 0;
foreach (GridViewRow gvRow in gv.Rows)
if (gvRow.RowType == DataControlRowType.DataRow)
{
HiddenField hf = (HiddenField)gvRow.FindControl("hfStudentID");
if (hf != null)
if (hf.Value.ToString().Length > 0)
wsDataRow +=1;
}
//if a count was generated then there are data rows, otherwise the rows are blank or nonexistant
if (wsDataRow > 0) return false;
else return true;
}
So running something like this will tell you if the Rows are really "
"DATA" rows, or empty or nothing!
Obviously in my case I have a HiddenField to tell me if the GridViewRow is an actual data row, as I prefill my gridview with blank rows (for my purposes) and some datarows.
However, a simpler version to check based on DataRow vs HeaderRow, etc...
foreach (GridViewRow gvRow in myGridView.Rows)
if (gvRow.RowType == DataControlRowType.DataRow)
{
//do what you need
}
I hope this helps.
In short, there is no GridView.IsEmpty() function unfortunately, unless you enumerate one as shown below.

Categories