I want to validate Gridview CheckBox Checked for Multiple Gridviews on the same page
I have tried the following but it is not working.
<script type="text/javascript">
var TargetBaseControl = null;
window.onload = function () {
try {
//get target base control.
TargetBaseControl = document.getElementById('<%= this.GridView1.ClientID%>', '<%= this.GridView2.ClientID%>');
}
catch (err) {
TargetBaseControl = null;
}
}
function TestCheckBox() {
if (TargetBaseControl == null) return false;
//get target child control.
var TargetChildControl = "chkSelectAdd";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl, 0) >= 0 &&
Inputs[n].checked)
return true;
alert('Select at least one checkbox!');
return false;
}
</script>
There are two problems that I can see here. document.getElementById only supports one element at a time, so your code will only check the first GridView's checkboxes. Also, an element's ID ought to be unique and so your check against the ID here:
Inputs[n].id.indexOf(TargetChildControl, 0) >= 0 &&
will only return true for the first checkbox.
I'd suggest removing the use of TargetBaseControl and simply relying on the names, rather than IDs, of the checkboxes instead:
var Inputs = document.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'checkbox' &&
Inputs[n].name.indexOf(TargetChildControl, 0) >= 0 &&
Inputs[n].checked)
return true;
...
Related
i need to create checkboxlist which should select max 4 items.
if user select the 5th item then it should clear particular 5th item only.
currently this code always clearing the first item of checkboxlist.
this is my c#:
protected void lstSalesPerson_SelectedIndexChanged(object sender, EventArgs e)
{
var items = from ListItem li in lstSalesPerson.Items
where li.Selected == true
select li;
Label1.Text = "";
for (int i = 0; i < lstSalesPerson.Items.Count; i++)
{
if (lstSalesPerson.Items[i].Selected == true)
{
if (items.Count() > 4)
{
Label1.Text = "checked maximum 4 items.";
lstSalesPerson.Items[i].Selected = false;
}
}
}
}
this is my html:
<asp:ListBox ID="lstSalesPerson" runat="server" SelectionMode="Multiple" AutoPostBack="true" OnSelectedIndexChanged="lstSalesPerson_SelectedIndexChanged"> </asp:ListBox>
you should reverse the loop as follows. In your loop it started from index[0] and check if total selected item is >4 if correct it will false the first item.
So the loop should be from the reverse index. so if 5 item selected then the first index selected will be [4] and it will get false
try below code
for (int i = lstSalesPerson.Items.Count-1; i >=0 ; i--)
{
if (lstSalesPerson.Items[i].Selected == true)
{
if (items.Count() > 4)
{
Label1.Text = "checked maximum 4 items.";
lstSalesPerson.Items[i].Selected = false;
}
}
}
i found answer using javascript it is as follows:
This might help someone: i'm using this control .multiselect-container > li > a > label > input because my control was rendered using this way in templates design. but you can use the logic for your code.. Thanks
$('.multiselect-container > li > a > label > input').click(function (e) {
var ddl = document.getElementById("<%=lstSalesPerson.ClientID%>");
if ($(this).prop('checked')) {
var count = 0;
for (var i = 0; i < ddl.options.length; i++) {
if (ddl.options[i].selected) {
count++;
if (count > 3) {
$(this).removeAttr('checked');
$(this).parent().parent().parent().prop('checked', false);
$(this).parent().parent().parent().prop('clicked', false);
$(this).parent().parent().parent().removeClass('active');
alert("You can select Max 4 sales person.");
return false;
}
}
}
}
});
I have a List of MyClass and in the main page I have 10 controls which will display the information about that list of Items. What I want is to check the count of the items in the List and then make the excess controls invisible. Now I'm using this code but is there an easier way of doing this?
if (myList.Count > 0)
{
Control1.MyClassInfo = myList[0];
if (myList.Count > 1)
{
Control2.MyClassInfo = myList[1];
if (myList.Count > 2)
{
// and like that till 10
}
else
{
Control3.Visible = false;
Control4.Visible = false;
// till 10
}
}
else
{
Control2.Visible = false;
Control3.Visible = false;
// till 10
}
}
else
{
Control1.Visible = false;
Control2.Visible = false;
Control3.Visible = false;
// and then till 10
}
Well, just add your controls in a list (ordered).
Something like that
var controlList = new List<Control>{ Control1, Control2, Control3 /*etc*/};
var count = myList.Count;
for (var i = 0; i < controlList.Count; i++) {
controlList[i].Visible = count > i;
}
You could create a list of your controls
List<Control> MyControls = new List<Control>{Control1, Control2,..,Control10};
and then
foreach(var C in MyControls)
C.Visible=false;
for(int i=0; i<myList.Count; i++)
C[i].Visible=true;
EDIT: for the more advanced coders here, this technique is called the Composite Pattern.
Basically, that's it. But you can improve on that basic concept in two ways:
1) use a collection
List<Control> _controls1to10;
Put your controls into that collection and write a method like this:
private void setVisibility(List<Control> _controls, bool visible)
{
foreach (Control c in _controls1to10)
{
c.Visible = visible;
}
}
This will make things easier.
2) use boolean expressions instead of nested ifs, like this:
bool hasElements = myList.Count > 0;
bool hasMoreThan1 = myList.Count > 1;
// ... and so on
This means that you have master switches at the top and use them in the following code. This is a fantasy example to clear the concept but does not apply to your code:
bool isEditable = User.LoggedIn && SystemState.Maintenance == false && item.Count > 0;
editButton.Visible = isEditable;
dropList.Visible = !isEditable;
I have one xtragrid control on my devxpress form . I've created the columns of my grid at runtime when i load the form . I'm developing the Field chooser for my grid view which is situated on the same form. For that i used the repositoryItemCheckedComboBoxEditcontrol & in that control i added the column names which will be present in the xtragrid.
Basically i created the columns to the xtragrid with the Visible property to false. When user checks particular column name by using repositoryItemCheckedComboBoxEdit then i set the Visible to true & again if user unchecked the column name then again i set the visible to false. & while creating column i set the width of the column.
Problem which i'm facing is that if user select the all fields from the repositoryItemCheckedComboBoxEdit then the grid control should show the horizontal scroll bar automatically when require.
And another problem is that with the columns is besides setting the width of the column, it is not showing the required width of that column . it shrinks that all column width .
code which i use for creating column to the xtragridview at run time is as follows -
public void AddGridColumn(string fieldName, string caption, int nRowWidth, RepositoryItem Item, object oCollection, string DisplayMember, string ValueMember, string format, FormatType type)
{
DevExpress.XtraGrid.Columns.GridColumn column = ColumnView.Columns.AddField(fieldName);
column.Caption = caption;
column.ColumnEdit = Item;
column.DisplayFormat.FormatType = type;
column.DisplayFormat.FormatString = format;
column.VisibleIndex = ColumnView.VisibleColumns.Count;
column.Width = nRowWidth;
}
code for the field chooser is as follows -
I used this function for filling the items of the repositoryItemCheckedComboBoxEdit control
private void FieldCollection()
{
allFields = new ArrayList();
columnNames = new Dictionary<string, string>();
allFields.Clear();
repositoryItemCheckedComboBoxEdit1.Items.Clear();
for (int i = 0; i < gvBase.Columns.Count; i++)
{
allFields.Add(gvBase.Columns[i].Caption );
if (gvBase.Columns[i].FieldName != "ContactID")
{
if (gvBase.Columns[i].Visible == true)
{
if (gvBase.Columns[i].Caption != "Label1" && gvBase.Columns[i].Caption != "Label2" && gvBase.Columns[i].Caption != "Label3" && gvBase.Columns[i].Caption != "Label4" && gvBase.Columns[i].Caption != "Label5")
repositoryItemCheckedComboBoxEdit1.Items.Add(gvBase.Columns[i].Caption, CheckState.Checked);
if (!columnNames.ContainsKey(gvBase.Columns[i].Caption))
columnNames.Add(gvBase.Columns[i].Caption, gvBase.Columns[i].FieldName);
}
else
{
if (gvBase.Columns[i].Caption != "Label1" && gvBase.Columns[i].Caption != "Label2" && gvBase.Columns[i].Caption != "Label3" && gvBase.Columns[i].Caption != "Label4" && gvBase.Columns[i].Caption != "Label5")
repositoryItemCheckedComboBoxEdit1.Items.Add(gvBase.Columns[i].Caption, CheckState.Unchecked);
if (!columnNames.ContainsKey(gvBase.Columns[i].FieldName))
columnNames.Add(gvBase.Columns[i].Caption, gvBase.Columns[i].FieldName);
}
}
}
cmbFieldChooser.EditValue = "";
}
this is used for the repositoryItemCheckedComboBoxEdit control event -
private void cmbFieldChooser_EditValueChanged(object sender, EventArgs e)
{
ArrayList temp = new ArrayList();
temp.AddRange(allFields);
string[] strFields = cmbFieldChooser.EditValue.ToString().Split(',');
for (int i = 0; i < strFields.Length; i++)
{
if (temp.Contains(strFields[i].Trim()))
temp.Remove(strFields[i].Trim());
if (strFields[i] != "")
{
if (columnNames.ContainsKey(strFields[i].Trim()))
{
if (gvBase.Columns[columnNames[strFields[i].Trim()]].Visible == false)
{
gvBase.Columns[columnNames[strFields[i].Trim()]].Visible = true;
gvBase.Columns[columnNames[strFields[i].Trim()]].BestFit();
}
}
}
}
if (temp.Count < 20)
{
for (int j = 0; j < temp.Count; j++)
{
if (columnNames.ContainsKey(temp[j].ToString().Trim()))
{
gvBase.Columns[columnNames[temp[j].ToString().Trim()]].Visible = false;
}
}
}
cmbFieldChooser.EditValue = repositoryItemCheckedComboBoxEdit1.GetCheckedItems();
if ((cmbFieldChooser.EditValue.ToString()).Split(',').Length > 5)
{
gvBase.OptionsView.ColumnAutoWidth = false;
gvBase.BestFitColumns();
gvBase.HorzScrollVisibility = ScrollVisibility.Always;
}
else
{
gvBase.OptionsView.ColumnAutoWidth = true;
gvBase.HorzScrollVisibility = ScrollVisibility.Never;
}
}
How to resolve this problem?
thanks.
How many columns do you have in your Grid?
I see you have code there to turn off the ColumnAutoWidth once you go past 5 columns (ie 6 columns or more). Have you debugged this condition to ensure the ColumnAutoWidth is indeed being turned off?
As per BestFitColumns Help Doc the BestFitColumns will only calculate for the first n rows as per the BestFitMaxRowCount property unless it it set to -1, could this be a cause?
The other thing that seems a little odd if that you are setting the EditValue of cmdFieldChooser within the cmdFieldChooser_EditValueChanged event... why so?
When CheckBox is unchecked in a ListView i need to get a popup window?
I have make a JS function and just pass id of your list like as
OnClientClick="return GetSelectedCheckBoxInGrid('grdCustomer');"
function GetSelectedCheckBoxInGrid(obj)
{
var con = 'ctl00_ContentPlaceHolder1_' + obj
var Parent = document.getElementById(con);
var TargetChildControl = "chk";
if (Parent==null)
{
return false;
}
var items = Parent.getElementsByTagName("input");
for(var n = 0; n < items.length; ++n)
if(items[n].type == 'checkbox' &&
items[n].id.indexOf(TargetChildControl,0) >= 0 &&
items[n].checked == false)
alert('Hi');return false;)
}
I think this is that
Not too sure about this, but hypothetically, you could give each checkbox a class, eg chkbox, and then have some jquery code to handle a click event:
$('chkbox').click(function() {
alert("here is where you put your popup code");
});
You could use window.open here
$('chkbox').click(function() {
if (! $('#chkbox').is(':checked'))
{
window.open ("http://www.javascript-coder.com","mywindow","status=1");
}
});
or
$('chkbox').click(function() {
if(! $('#chkbox').attr('checked'))
{
window.open ("http://www.javascript-coder.com","mywindow","status=1");
}
});
How to check whether a checkbox is checked in jQuery?
I have used checkbox column in gridview. I want to check status of that checkboxes. On click of a button it should be checked that if any checkbox is checked or not. If none checkbox is checked then it should display alert message that check checkbox first.
Hey, I found answer. It is as follows:
function checkBoxselectedornot()
{
var frm=document.forms['aspnetForm'];
var flag=false;
for(var i=0;i<document.forms[0].length;i++)
{
if(document.forms[0].elements[i].id.indexOf('chkDownloadSelectedEvent')!=-1)
{
if(document.forms[0].elements[i].checked)
{
flag=true
}
}
}
if (flag==true)
{
return true
}else
{
alert('Please select at least one Event.')
return false
}
}
protected void OnCheckedChanged(object sender, EventArgs e)
{
bool flag = false;
foreach (GridViewRow row in Grid_InvoiceGarden.Rows)
{
CheckBox chkItem = (CheckBox)row.FindControl("chkSelect");
if (chkItem.Checked)
flag = true;
}
if (flag == true)
{
btnUpdate.Visible = true;
}
else
{
btnUpdate.Visible = false;
}
}
if(document.getElementById('checkBoxId').checked) {
//checked
} else {
//not checked
}
edit: if you want to check all checkboxes of a form you can loop through the collection:
var inputs = document.getElementById('formId').getElementsByTagName('input');
var isChecked = false
for( var i = 0; i < inputs.length; i++) {
if(inputs[i].type == 'checkbox' && inputs[i].checked) {
isChecked = true;
}
}
if(isChecked) {
//at least one checkbox checked
}
Server side:
//in your button click event :
bool flag = false;
for( int i=0; i < gridview1.rows.count ; i++)
{
if(checkbox1.checked)
flag = true;
}
if(flag)
{
//means atleast one check box is checked
}
You will have to add some custom Javascript to your page for the client-side alert to show. Here's a method that I've written that works with a GridView called 'GridView1' (this should be the default name if you've just dragged the control onto your ASPX page):
<script type="text/javascript">
function ClientCheck() {
var valid = false;
var gv = document.getElementById("GridView1");
for (var i = 0; i < gv.all.length; i++) {
var node = gv.all[i];
if (node != null && node.type == "checkbox" && node.checked) {
valid = true;
break;
}
}
if (!valid) {
alert("Invalid. Please select a checkbox to continue.");
}
return valid;
}
</script>
You can see that it sets a variable to the GridView control to start with, then iterates through all the children in a for loop. If the child is a checkbox and it is checked, then we set the valid variable to true. If we get to the end of the iteration and no checked checkboxes are found, then valid remains false and we execute the alert.
To link this into your GridView on your ASPX page, first make the button column a TemplateField and surround the LinkButton with your client-side code. If you've used the designer to set up your columns, you can use the "Convert this field into a TemplateField" link in the column editor). Here's an example of the source you'll end up with:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1">
<Columns>
<asp:TemplateField HeaderText="Button Field" ShowHeader="False">
<ItemTemplate>
<span onclick="return ClientCheck();">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="IDClick" Text='<%# Eval("YourDataSourceItem") %>'></asp:LinkButton>
</span>
</ItemTemplate>
</asp:TemplateField>
// ...your remaining columns...
Using the TemplateField lets us add any client-side code we like. Here we're adding a span and using onclick to call our ClientCheck method.
If you aren't bothered about the alert, you could achieve your aims by using a CustomValidator control, which executes on the server-side.
I hope this helps.
<script type="text/javascript" language="javascript">
function CheckboxSelect() {
var LIntCtr;
var LIntSelectedCheckBoxes = 0;
for (LIntCtr = 0; LIntCtr < document.forms[0].elements.length; LIntCtr++) {
if ((document.forms[0].elements[LIntCtr].type == 'checkbox') && (document.forms[0].elements[LIntCtr].name.indexOf('chkID') > -1)) {
if (document.forms[0].elements[LIntCtr].checked == true) {
LIntSelectedCheckBoxes = parseInt(LIntSelectedCheckBoxes) + 1;
}
}
}
if (parseInt(LIntSelectedCheckBoxes) == 0) {
alert('User(s) Must Be Selected For operation !');
return false;
}
}
</script>