Checkbox in gridview - c#

As I have check box in gridview if i dont select any one checkbox and if i click asp button then i have to show message to user to select checkbox
awaiting response

Should be something like you need...
Boolean Selected = false;
for (int count = 0; count < grd.Rows.Count; count++)
{
if (((CheckBox)grd.Rows[count].FindControl("yourCheckbox")).Checked)
{
Selected = true;
}
}
if (Selected == false)
{
//your message goes here.
}
if you need javascript code...
function CheckIfSelect() {
var frm = document.forms[0];
var Selected=false;
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].type == "checkbox") {
if(frm.elements[i].checked)
{
Selected=true;
break;
}
}
if(Selected==false)
{
//your message goes here
}
}
}

If you want to do this client side you could use a library like jQuery to iterate through the checkboxes.
If you want to do this server side, you will need to reenumerate the controls on postback, and check the Checked value. Alternatively if this GridView binds to a DataSource, check the posted back values within the DataSource.

Related

Validate GridView with CheckBox (at least one checked) c# window application

i am working on a c# window application. i am phasing an issue regarding on button save. How to Validate GridView with CheckBox (at least one checked) in c# windowform application on save button? kindly show with example
{
// var checkbox = Convert.ToBoolean(this.dgvPurchaseOrder.Rows[0].Cells["checkBoxColumn"].Value);
for (int i = 0; i < dgvPurchaseOrder.Rows.Count; i++)
{
var checkbox = Convert.ToBoolean(this.dgvPurchaseOrder.Rows[0].Cells["checkBoxColumn"].Value);
if)
{
MessageBox.Show("Alteast Check one record to save");
}
else
{
proceed
}
}
Use foreach for better performance,
string message = "Alteast Check one record to save";
int i=0;
foreach (DataGridViewRow row in dgvPurchaseOrder.Rows)
{
bool isSelected = Convert.ToBoolean(row.Cells["checkBoxColumn"].Value);
if (isSelected)
{
message = "YES";
i++;
}
}
if(message!="YES")
MessageBox.Show(message);
else
MessageBox.Show(i.ToString()+" Items Selected");

ViewState to compare CheckBoxList Selected Values

I have a button that creates a CheckBoxList. The items in the CheckBoxList are selected based on a user's current notification subscriptions. I'm storing the true or false value of the selected item.
After the users change their subscriptions by checking or unchecking a box in the CheckBoxList, they click another button to update their notification subscriptions. I need to compare the Viewstate["PREV"] with the changed selections on postback and run some functions based on the changes.
ArrayList list = new ArrayList();
for (int i = 0; i < checkBoxList1.Items.Count; i++)
{
list.Add(checkBoxList1.Items[i].Selected.ToString());
}
ViewState["PREV"] = list;
Even though I can't see the values with a Response.Write, the values for the ViewState are correct when I add a watch in debug.
The problem I'm having is how to approach the next step to do the comparison. This is what I want to accomplish:
for (int i = 0; i < checkBoxList1.Items.Count; i++)
{
//if checkbox state goes from false to true, subscribe to topic
//mySubscribeMethod
//else if checkbox state goes from true to false, unsubscribe to topic
//myUnsubscribeMethod
//else if checkbox state is unchanged, do nothing
}
You can try something like this
ArrayList list = ViewState["PREV"] as ArrayList;
for (int i = 0; i < checkBoxList1.Items.Count; i++)
{
if (checkBoxList1.Items[i].Selected == true && Convert.ToBoolean(list[i]) == false)
{
// Subscribe Method
}
if (checkBoxList1.Items[i].Selected == false && Convert.ToBoolean(list[i]) == true)
{
// Unsubscribe Method
}
else
{
// Continue to loop
}
}

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

How to Get cell index in gridview

I'm using a website(asp.net,C#) to view some details in gridview. In that gridview I have generated checkboxes dynamically. So it will be placed any cell inside of that gridview. I find that control in grdview by using FindControl(), but I cant get that cell index... now I want to get that excact cell index which placed that checkbox. How shall I get that cell index?
Please anyone Tell me the solution of this problem.
Thanks in advance.
My code for getting that Control is:
if (HeaderCell.Text.Contains(strColumnName))
{
CheckBox chk = GrdDynamicControls.Rows[index].FindControl(chkCheckBox1.ID) as CheckBox;
chk.Checked = true;
strCelValue = chk.Checked.ToString();
}
Try this:
int theCellNumberWhatINeed = -1;
for (int cellNumber = 0; cellNumber < GridView1.Rows[index].Cells.Count; cellNumber++)
{
foreach (Control ctrl in GridView1.Rows[index].Cells[cellNumber].Controls)
{
if (ctrl.ID == "aCheckBox") // or compare by clientid... etc
{
theCellNumberWhatINeed = cellNumber;
break;
}
}
}
if (theCellNumberWhatINeed > -1)
{
// ...
}
Not the most elegant solution but works with the builtin gridview control without creating your own.
You can use Event Args e
e.Item.ItemIndex
it will return an integer
Hope this will help

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>

Categories