I have a devexpress gridview, and in one of the columns is a checkbox. I want to check to see if the checkbox in that column is selected in the focused row, and if so, perform some action. How should I go about checking if the checkbox is checked?
bool value = (bool) gridView.GetRowCellValue(gridView.FocusedRowHandle, column);
If you are using DataBinding it is very easy. For example:
public class MyClass(){
public MyClass(){
}
public bool IsTrue
{
get{;}
set{;}
}
}
List<MyClass> manyMyClassObjects = new List<MyClass>();
//Add some values for sure
GridControl.DataSource = manyMyClassObjects;
Now the IsTrue property is binded to the Grid. The GridView just present the underlaying Data. If you change a value in the Grid it changes the value of your DataSource Object. This will work with any Property which implements a setter for sure.
DataRow[] rows = new DataRow[gvExcelSheet.RowCount];
for (int j = 0; j < gvExcelSheet.RowCount; j++)
{
rows[j] = gvExcelSheet.GetDataRow(j);
if ((bool)rows[j]["yourcheckboxcolumnname"] == true)
{
//your code
}
}
Simple as below:
bool value = Convert.ToBoolean(gvMain.SelectedRowsCount);
Related
I am working with winform project. i have two datagridview which has same number of columns and same structure. frist column is checkbox column.
here is code to bind two datagrid with same kind of data.
List<AllGroupNames> grpDtl = GetAllGroups(Nodes);
List<AllGroupNames> grpDtl1 = GetAllGroups(Nodes); //grpDtl.GetRange(0, grpDtl.Count);
//bind two grid with all groups name
if (_grpDtl != null && _grpDtl.Count > 0)
{
dgSingleGroups.AutoGenerateColumns = false;
dgSingleGroups.DataSource = grpDtl;
dgSingleGroups.Columns[0].DataPropertyName = "Select";
dgSingleGroups.Columns[1].DataPropertyName = "GroupName";
dgSingleGroups.Columns[1].ReadOnly = true;
dgSingleGroups.Columns[0].Width = 47;
dgSingleGroups.Columns[1].Width = 346;
dgAllGroups.AutoGenerateColumns = false;
dgAllGroups.DataSource = grpDtl1;
dgAllGroups.Columns[0].DataPropertyName = "Select";
dgAllGroups.Columns[1].DataPropertyName = "GroupName";
dgAllGroups.Columns[1].ReadOnly = true;
dgAllGroups.Columns[0].Width = 47;
dgAllGroups.Columns[1].Width = 346;
}
grpDtl1 = null;
grpDtl = null;
_grpDtl = null;
GetAllGroups() iterate in treeview node collection and accumulate node name.
private List<AllGroupNames> GetAllGroups(TreeNodeCollection tnCollection)
{
//accumulate group name in recursive fashion
foreach (TreeNode tn in tnCollection)
{
if (tn.Tag != null)
{
if (((object)tn.Tag).GetType().ToString().Contains("TunerDetails"))
{
_grpDtl.Add(new AllGroupNames { Select = false, GroupName = tn.Text });
}
GetAllGroups(tn.Nodes);
}
}
return _grpDtl;
}
Now problem is when i check second grid checkbox then my first grid checkbox is getting checked invisibly means when i am reading first grid's first column value in loop then i am getting checkbox value true. where as i have not checked my first grid's any checkbox.
when i select any row of second grid that same row is getting automatically selected in first grid.
I just select one row from right side grid and same row of left side grid automatically gets selected....which is problem for me. Why two grid syncing automatically. screen shot attached.
why it is happening i am not able to capture the reason. please help me what to change in code to get rid of this problem.
Apparently every object of class AllGroupName has a Boolean property Select.
You created Column[0] such, that the checkbox is checked whenever this boolean is true, and vice versa: whenever the operator checks this checkbox, the corresponding AllGroupName.Select will become true.
You decided to use the same DataSource as object in two DataGridViews.
Operator checks the checkbox of row[4] in Dgv1
This means that DataSource[4].Select = true;
This means that all objects that have this DataSource will be notified that [4] has changed
Row[4] in Dgv1 and Dgv2 will be updated: checkbox is checked.
If you don't want that changes in Dgv1 are refelected in Dgv2, then you should make a copy of the datasource.
List<...> data1 = ...; // shouldn't this be an BindingList<...> ?
Dgv1.DataSource = data1;
List<...> data2 = new List<...>(data1); // clone data1
Dgv2.DataSource = data2;
How can I call my function in this data gridview? I would like to make the sum of these two to be displayed in the highlighted datagridview:
foreach (DataRow row in dt.Rows) {
datagridview_information.Rows.Add();
datagridview_information.Rows[counterSelected].Cells[0].Value = row["BrandName"].ToString();
datagridview_information.Rows[counterSelected].Cells[1].Value = row["GenericName"].ToString();
datagridview_information.Rows[counterSelected].Cells[2].Value = row["PresDayOfIntake"].ToString();
datagridview_information.Rows[counterSelected].Cells[3].Value = row["Status"].ToString();
datagridview_information.Rows[counterSelected].Cells[4].Value = "5";
datagridview_information.Rows[counterSelected].Cells[5].Value = medicineLeft();
datagridview_information.Rows[counterSelected].Cells[7].Value = row["ContainerNumber"].ToString();
datagridview_information.Rows[counterSelected].Cells[8].Value = row["Status"].ToString(); ;
counterSelected++;
}
}
}
public int medicineLeft()
{
for (int i = 0; i < datagridview_schedule.Rows.Count; ++i)
{
medleft += Convert.ToInt32(datagridview_information.Rows[i].Cells[8]) - Convert.ToInt32(datagridview_medicine.Rows[i].Cells[4]);
datagridview_information.Rows[i].Cells[5].Value = Convert.ToString(medleft);
}
return medicineLeft();
}
You're going to have to give more code here, I have absolutely no idea what you're trying to do. Is medleft declared elsewhere?
Your medicineLeft() method is returning itself, meaning it'll run as an infinite loop and will probably throw a StackOverflow exception on this line:
datagridview_information.Rows[counterSelected].Cells[5].Value = medicineLeft();
Your medicineLeft method needs to return an integer - is it meant to return medleft? If so, changing it to return medleft; should fix this.
One easy solution would be to change the way you populate the DataGridView. If I were doing this, I would do the following:
Create a class object to store the data you want in your grid:
public class Medicine
{
public string BrandName { get; set; }
public string GenericName { get; set; }
<... add other properties ...>
}
Instantiate a collection of Medicine objects that you want to bind to the DataGridView.
public List<Medicine> GetMedicine(DataRowCollection rows)
{
List<Medicine> medicines = new List<Medicine>();
foreach (DataRow row in rows)
{
Medicine medicine = new Medicine();
medicine.BrandName = row["BrandName"] == null ? string.Empty : row["BrandName"].ToString();
medicine.GenericName = row["GenericName"] == null ? string.Empty : row["GenericName"].ToString();
//more rows here to populate Medicine object
//include the call to whatever methods are needed to populate the object
medicines.Add(medicine);
}
return medicines;
}
Bind the collection to the DataGridView
datagridview_information.DataSource = GetMedicines(dt.Rows);
I find it easy to create the DataGridView control on the form, set the columns in the designer, and set the AutoGenerateColumns property to false in code so that the grid appears as I wish. It is up to you how you want to handle that.
dropdownlist always show the first index of Item populated from database and in debug mode ddlcountry.Text always empty string("").
I have "Philippines" item in my dropdownlist but "Argentina" always shown first in my dropdown instead of "Philippines".
Please help.
//in formload
if(!isPostback)
{
DataTable dtCountry= new DataTable();
dtCountry= network.GetCountry();
for (int row = 0; row < dtCountry.Rows.Count; row++)
{
ddlCoutry.Items.Add(new ListItem { Text = dtCountry.Rows[row][1].ToString(), Value = dtCountry.Rows[row][1].ToString() });
}
}
ddlCountry.Text = "Philippines";
As I mentioned in the comment above, I think your problem is you are trying to select the dropdown option by text but getting confused with .Text property. You can do this:-
ddlCountries.Items.FindByText("Philippines").Selected = true;
Set the selected item to "Philippines" because I assume your list of countries is in alphabetical order.
ddlCountry.SelectedIndex = ddlCountry.Items.IndexOf(ddlCountry.Items.FindByText("Philippines"));
Also I want to point out your variable is misspelled:
**ddlCoutry**.Items.Add(new ListItem { Text = dtCountry.Rows[row][1].ToString(), Value = dtCountry.Rows[row][1].ToString() });
i am using CheckedListBox so that user can multi select items for this i am populating CheckedListBox dynamically from database Here is CheckedListBox Filling Method
public void FillSubjectsCombo()
{
DataTable dt = objSubCls.FillSubjects();
chkLstBxClass_FrmSubjecClassRelation.DataSource = dt;
chkLstBxClass_FrmSubjecClassRelation.DisplayMember = "Subjects";
chkLstBxClass_FrmSubjecClassRelation.ValueMember = "SubId";
chkLstBxClass_FrmSubjecClassRelation.Enabled = true;
for (int i = 0; i < dt.Rows.Count; i++)
{
//Here i am setting Every item Checked
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(i, CheckState.Checked);
}
}
On the Same Windows Form I have DataGridView i Want when i double click any row of datagrid then from selected row get value and from that value make respected item checked in CheckedListBox and other item UnChecked
Here is the DataGridView Event
private void dgv_FrmSubjectClassRelation_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
string classId = dgv_FrmSubjectClassRelation.CurrentRow.Cells[3].Value.ToString();
string className = dgv_FrmSubjectClassRelation.CurrentRow.Cells[4].Value.ToString();
foreach (int i in chkLstBxClass_FrmSubjecClassRelation.CheckedIndices)
{
//Here I am UnChecking Every Checked Item
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(i, CheckState.Unchecked);
}
My Question : How to Checked The Specific Item When Double Clicking DataGridView
Update: I am binding My DataGridView Like This
for (int i = 0; i < dt.Rows.Count; i++)
{
dgv_FrmSmstrClsAssign.Rows.Add();
dgv_FrmSmstrClsAssign.Rows[i].Cells[0].Value = dt.Rows[i].ItemArray[0];//Acadmc Yr
dgv_FrmSmstrClsAssign.Rows[i].Cells[1].Value = dt.Rows[i].ItemArray[1];// Semester Name
dgv_FrmSmstrClsAssign.Rows[i].Cells[2].Value = dt.Rows[i].ItemArray[2]; //College
dgv_FrmSmstrClsAssign.Rows[i].Cells[3].Value = dt.Rows[i].ItemArray[3];//Class
dgv_FrmSmstrClsAssign.Rows[i].Cells[4].Value = dt.Rows[i].ItemArray[4]; //Entry Date
dgv_FrmSmstrClsAssign.Rows[i].Cells[5].Value = dt.Rows[i].ItemArray[5];//IsActive
dgv_FrmSmstrClsAssign.Rows[i].Cells[6].Value = dt.Rows[i].ItemArray[6];//AcadmicYr Id
dgv_FrmSmstrClsAssign.Rows[i].Cells[7].Value = dt.Rows[i].ItemArray[7];//Semster Id
dgv_FrmSmstrClsAssign.Rows[i].Cells[8].Value = dt.Rows[i].ItemArray[8];//Semster Id
}
I was unable to find any method that allows you to easily map the bound value, so you will have to use IndexOf method of Items collection to obtain the index and then manually check-uncheck the items.
To obtain the bound item from DataGridView row you can use DataGridViewRow.DataBoundItem property:
private void CheckSelectedItem()
{
// Get bound item object from datagrid
object item = dgv_FrmSubjectClassRelation.CurrentRow.DataBoundItem;
// Get corresponding index in listView
Int32 itemIndexInCheckedListView = chkLstBxClass_FrmSubjecClassRelation.Items.IndexOf(item);
// Check the item in listView
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(itemIndexInCheckedListView,
CheckState.Checked);
}
private void dgv_FrmSubjectClassRelation_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
string classId = dgv_FrmSubjectClassRelation.CurrentRow.Cells[3].Value.ToString();
string className = dgv_FrmSubjectClassRelation.CurrentRow.Cells[4].Value.ToString();
foreach (int i in chkLstBxClass_FrmSubjecClassRelation.CheckedIndices)
{
//Here I am UnChecking Every Checked Item
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(i, CheckState.Unchecked);
}
// --------------Check the selected item----------------
this.CheckSelectedItem();
}
EDIT:
What you do is not exactly binding (well, it is binding, just not as Windows Forms defines it), so the previous solution won't work for you. If both your DataTable and DataGridView contain primary key or another unique identifier, then it is possible to map CurrentRow to the Item in DataTable:
private void CheckSelectedItem()
{
// Get bound item object from datagrid
object uniqueKey = dgv_FrmSubjectClassRelation.
CurrentRow.
Cells["SOME UNIQUE VALUE COLUMN"].
Value;
// Adapting http://stackoverflow.com/a/9300237/3745022 - there are more simple LINQless
// solutions for this situation, but it is not important for the concept.
Int32 itemIndexInCheckedListView = chkLstBxClass_FrmSubjecClassRelation.
Items.
Select((value, index) => new { value, index }).
Where(pair => pair.value.UniqueValue == uniqueKey ).
Select(pair => pair.index + 1).
FirstOrDefault() - 1;
// Check the item in listView
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(itemIndexInCheckedListView,
CheckState.Checked);
}
If you do not have such Unique column you may want to add it(just make it hidden)
OR even better - use full-blown DataBinding - http://msdn.microsoft.com/en-us/library/fbk67b6z(v=vs.90).aspx;
Need some help since I'm still a newbie in programming. I have a gridview that has five columns, the three columns composed of checkboxes. Then I need to get these checkboxes value if they were checked and put it in IList. My problem is how to implement it when adding it to my IList. Please help. See my code below. I know something is wrong.
public IList<Title> Checkboxes
{
get
{
CheckBox chkEPS;
CheckBox chkIMDF;
CheckBox chkPS;
IList<Title> checkedList = new List<Title>();
foreach (GridViewRow row in gvwTitles.Rows)
{
chkABC = (CheckBox)row.FindControl("chkABC");
chkABCD = (CheckBox)row.FindControl("chkABCD");
chkABCDE = (CheckBox)row.FindControl("chkABCDE");
if ((chkABC.Checked) && (chkABCD.Checked) && (chkABCDE.Checked))
{
checkedList.Add(new Title(What will be the value));
// how will I add the value, I am also considering what if the user check the chkABC checkbox, while the others were not checked??
}
}
return checkedList;
}
}
public Title(int id, bool _isPocketSharing, bool _isPreventSplitting, bool _isMissingDataFile)
I assume that you want to add title prperty on the basis of checkbox or checked or not
you can user ternary operator for this ? :
i think you need this
public IList<Title> Checkboxes
{
get
{
CheckBox chkEPS;
CheckBox chkIMDF;
CheckBox chkPS;
IList<Title> checkedList = new List<Title>();
foreach (GridViewRow row in gvwTitles.Rows)
{
chkABC = (CheckBox)row.FindControl("chkABC");
chkABCD = (CheckBox)row.FindControl("chkABCD");
chkABCDE = (CheckBox)row.FindControl("chkABCDE");
checkedList.Add(new Title(1 , chkABC.Checked ? true : false, chkABCD.Checked ? true : false, chkABCDE.Checked ? true : false));
}
return checkedList;
}
}
Try this:
checkedList.Add(new Title{name=1 ,name2=??,name3= ??, name4=??});//name,name1,name2,name..is suppose to your property of class "Title"