I have a strange issue.
Basically I have a datagridview and a button. When I click this button it checks all rows for column 1s value - the checkbox column. It then sets it to true / false depending on what it currently is.
Thats all fine.
But then, I have another button to do something with these rows that are ticked. I click it and it only ever identifies the first row as being ticked. The rest are apparently null now..?
So, how can I programmtically set the value of a checkbox column in a datagrid view and then read it again cause Im apparently way off the mark based on my results.
This sets the tick boxs and I can see them, untick them manually etc.
foreach (DataGridViewRow row in dgv.Rows)
{
var ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (ch1.Value == null)
ch1.Value = false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = false;
break;
case "False":
ch1.Value = true;
break;
}
}
Then the next button to check values is just finding nulls
foreach (DataGridViewRow row in rows)
{
var ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (ch1.Value == null)
ch1.Value = false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = true;
break;
case "False":
ch1.Value = false;
break;
}
var val = row.Cells["EbayListingID"].Value.ToString();
if (ch1.Value.ToString() == "true") continue;
var listing = dsEntities.EbayListings.First(x => x.EbayListingID.ToString() == val);
SubmitListingForReview(listing, false);
}
First,
if (ch1.Value.ToString() == "true") continue;
Why is string constant is "true", but not "True"?
Second, in the next button click handler, what is it "rows"?
foreach (DataGridViewRow row in rows)
I try this code and it works fine :
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (ch1.Value == null)
ch1.Value = false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = false;
break;
case "False":
ch1.Value = true;
break;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (ch1.Value == null)
ch1.Value = false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = true;
break;
case "False":
ch1.Value = false;
break;
}
var val = row.Cells[1].Value;
if (ch1.Value.ToString() == "True") continue;
MessageBox.Show("1");
}
}
Related
Basically I am writing a simple phone directory. This application has a listview window, a search (text) window and a button to search. Once the user inputs a name in the search window and hit the search button, the program selects and highlight all users corresponding to the search criteria.
No problem….
A unique scenario developed however if the user selects another item in the listview window. The previous items found are/will be still highlighted…
How can I deselect/remove the highlight on the found items whenever/ifever the user select another item immediately after the search?
Below is the code attached to the search button:
Thanks in advance
private void button3_Click(object sender, EventArgs e){
string s = " Search Via Forename";
int result = 0;
int count = 0;
result = string.Compare(textBox1.Text, s);
switch ((result == 0) || (String.IsNullOrEmpty(textBox1.Text))){
case true: MessageBox.Show("Please input forename...");
break;
default: foreach (ListViewItem item in listView1.Items){
if (item.Text.ToLower().StartsWith(textBox1.Text.ToLower())){
item.Selected = true;
item.BackColor = Color.CornflowerBlue;
item.ForeColor = Color.White;
count++;
}else{
item.Selected = false;
item.BackColor = Color.White;
item.ForeColor = Color.Black;
}
}
if (listView1.SelectedItems.Count == 1){
listView1.Focus();
}
textBox1.Text = " Search Via Forename";
textBox1.ForeColor = Color.Silver;
break;
}
}
Before your highlightning code, make a loop through all the items and set their item.Selected to false.
foreach (ListViewItem item in listView1.Items){
if (item.Selected)
item.Selected = false;
}
First removed the selection piece of your code. In fact I would just clear selections all together. The color change that your doing is effectively doing the highlighting for you, so from the information you've provided I don't think its necessary to select them.
private void button3_Click(object sender, EventArgs e){
string s = " Search Via Forename";
int result = 0;
int count = 0;
result = string.Compare(textBox1.Text, s);
switch ((result == 0) || (String.IsNullOrEmpty(textBox1.Text))){
case true: MessageBox.Show("Please input forename...");
break;
default: foreach (ListViewItem item in listView1.Items){
item.Selected = false;
if (item.Text.ToLower().StartsWith(textBox1.Text.ToLower())){
item.BackColor = Color.CornflowerBlue;
item.ForeColor = Color.White;
count++;
}else{
item.BackColor = Color.White;
item.ForeColor = Color.Black;
}
}
if (listView1.SelectedItems.Count == 1){
listView1.Focus();
}
textBox1.Text = " Search Via Forename";
textBox1.ForeColor = Color.Silver;
break;
}
}
Next I would use the selection changed event to detect when a selection was made and clear all the formatting I did.
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListViewItem item in listView1.Items)
{
item.BackColor = Color.White;
item.ForeColor = Color.Black;
}
}
You didn't specify win forms or WPF so I assumed win forms and made an example that way. If your using WPF i believe the event you would need to subscribe to is the OnSelectionChanged event for the list view control.
After looking at the code a bit more, I realize your using a switch statement to handle a Boolean operation which is not correct. I've added how I would have changed that check below.
private void button3_Click(object sender, EventArgs e)
{
string s = " Search Via Forename";
int result = 0;
int count = 0;
result = string.Compare(textBox1.Text, s);
// Do the check on the input
if ((result == 0) || (string.IsNullOrEmpty(textBox1.Text)))
{
MessageBox.Show("Please input forename...");
// after notifying the user just return
return;
}
foreach (ListViewItem item in listView1.Items)
{
item.Selected = false;
if (item.Text.ToLower().StartsWith(textBox1.Text.ToLower()))
{
item.BackColor = Color.CornflowerBlue;
item.ForeColor = Color.White;
count++;
}
else
{
item.BackColor = Color.White;
item.ForeColor = Color.Black;
}
}
if (listView1.SelectedItems.Count == 1)
{
listView1.Focus();
}
}
Several places in my program, the RadioButton matching the selected item has to be checked, and I have a lot of if statements like so:
DataRowView TempRow = (DataRowView)ScheduleDataGrid.SelectedItem;
if (Convert.ToString(TempRow["Bio"]) == "Bio1")
{
BioRB1.IsChecked = true;
}
if (Convert.ToString(TempRow["Bio"]) == "Bio2")
{
BioRB2.IsChecked = true;
}
if (Convert.ToString(TempRow["Bio"]) == "Bio3")
and so on... I want to replace all this with something short and smart.
I tried using the number of the bio to relate to the button like so:
string bioselected = Convert.ToString(TempRow["Bio"]);
int i = Convert.ToInt16(bioselected.Substring(bioselected.Length - 1, 1));
BioRB[i].IsChecked = true;
but doing a BioRB[i] doesn't work, it ignores the [i] and says BioRB does not exist. Any other suggestions?
BioRB[i] is not doing anything like what you think it's doing. All variable references (controls included) have to be well-defined at compile time - you can't refer to a control's name by building a string that matches the name.**
Try creating a list of your radio buttons. Then you can index into the list:
List<RadioButton> radioButtons = new List<RadioButton>()
{
BioRB1,
BioRB2
};
string bioselected = Convert.ToString(TempRow["Bio"]);
int i = Convert.ToInt16(bioselected.Substring(bioselected.Length - 1, 1));
radioButtons[i].IsChecked = true;
** Technically you can do this via reflection, but it's far more complex than what you've tried.
Maybe this will look better:
string caseSwitch = Convert.ToString(TempRow["Bio"]);
switch (caseSwitch)
{
case "Bio1":
BioRB1.IsChecked = true;
break;
case "Bio2":
BioRB2.IsChecked = true;
break;
case "Bio3":
BioRB3.IsChecked = true;
break;
default:
Console.WriteLine("Default case...is optional");
break;
}
Also, try doing what Alybaba726 said and use CellContentClick or something like this:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if(e.ColumnIndex == dgv.Columns["Bio"].Index)
{
string bioSelected = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
switch (bioSelected)
{
case "Bio1":
BioRB1.IsChecked = true;
break;
case "Bio2":
BioRB2.IsChecked = true;
break;
case "Bio3":
BioRB3.IsChecked = true;
break;
default:
Console.WriteLine("Default case...this is optional");
break;
}
}
}
I have this code:
// code above
checkBox1.Checked = false;
checkBox2.Checked = false;
checkBox3.Checked = false;
checkBox4.Checked = false;
checkBox5.Checked = false;
checkBox6.Checked = false;
checkBox7.Checked = false;
checkBox8.Checked = false;
checkBox9.Checked = false;
//code below
I have 320 checkBoxes to set cleared/false.
How do I control checkBox(variable)?
I would like to do the following:
for (int counter=1; counter<321; counter++)
{
checkBox***Put counter Variable Here***.Checked = false;
}
If all the checkboxes are incremental, then you can use the Control.ControlCollection.Find Method.
for (int counter=1; counter<321; counter++)
{
var ctrl = this.Controls.Find("checkbox" + counter, true).FirstOrDefault() as CheckBox;
if (ctrl != null)
{
ctrl.Checked = false;
}
}
If you just want to set every checkbox, then filter the Controls collection:
var checkBoxes = this.Controls.OfType<CheckBox>();
foreach (CheckBox cbx in checkBoxes)
{
cbx.Checked = false;
}
You can loop through all of the controls on the form and check for check boxes.
foreach (Control ctrl in Controls)
{
if (ctrl is CheckBox)
{
((CheckBox)ctrl).Checked = false;
}
}
void SetAllCheckBoxesState(Boolean isChecked) {
foreach(Control c in this.Controls) {
CheckBox cb = c as CheckBox;
if( cb != null ) cb.Checked = isChecked;
}
}
I have a Datagridview within a windows form which loads data. I have also included a checkbox column to this Datagridview in run time. My question is how can i know if any of the checkboxs from the checkbox column has been checked, and if a checkbox has been checked enable a button. I have used CellValueChanged event to perform above task but unable to get the desired result.
This is what i have done
List<int> ChkedRow = new List<int>();
for (int i = 0; i <= Datagridview1.RowCount - 1; i++)
{
if (Convert.ToBoolean(Datagridview1.Rows[i].Cells["chkcol"].Value) == true)
{
button1.Enabled = true;
}
else
{
button1.Enabled = false;
}
}
set false before the loop
button1.Enabled = false;
when you found checked item, set it as Enabled true and break the loop
button1.Enabled = true;
break;
code:
button1.Enabled = false;
for (int i = 0; i <= Datagridview1.RowCount - 1; i++)
{
if (Convert.ToBoolean(Datagridview1.Rows[i].Cells["chkcol"].Value))
{
button1.Enabled = true;
break;
}
}
Or you can do below as well
button1.Enabled = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell cell = row.Cells[colCheckIndex] as DataGridViewCheckBoxCell;
if (cell.Value == cell.TrueValue){
button1.Enabled = true;
break;
}
}
Try this code
button1.Enabled = false;
foreach (DataGridViewRow row in Datagridview1.Rows)
{
if (((DataGridViewCheckBoxCell)row.Cells["chkcol"]).Value)
{
button1.Enabled = true;
break;
}
}
or
//This will always call the checking of checkbox whenever you ticked the checkbox in the datagrid
private void DataGridView1_CellValueChanged(
object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == [Your column index])
CheckForCheckedValue();
}
private void CheckForCheckedValue()
{
button1.Enabled = false;
foreach (DataGridViewRow row in Datagridview1.Rows)
{
if (((DataGridViewCheckBoxCell)row.Cells["chkcol"]).Value)
{
button1.Enabled = true;
break;
}
}
}
NOTE
Don't forget to check the for Null value and do something if it is NULL
i've got an event handler for columncontentclicked and it works fine, until i shorten the datalist with stored procedure. after that the indexnum that is return is 0 instead of 5 or 6.
Do i have to refresh datagridview or something?
here's te code
:
int lastcol = dataGridView1.Columns.Count;
// MessageBox.Show(e.ColumnIndex.ToString() + lastcol.ToString());
if (e.ColumnIndex == lastcol - 1)
{
int index = int.Parse(dataGridView1.CurrentRow.Cells[0].Value.ToString());
Global.size = this.Size;
Global.position = this.Location;
Global.overzicht_select = index.ToString();
if (Global.give_return == false)
{
switch(type)
{
case 1:
Global.edit_form_proj = false;
project_form project_form1 = new project_form(this);
project_form1.Show(this);
this.Hide();
break;
case 2:
Global.edit_form_bedr = false;
bedrijf_form bedrijf_form1 = new bedrijf_form(this);
bedrijf_form1.Show(this);
this.Hide();
break;
case 3:
Global.edit_form_pers = false;
persoon_form persoon_form1 = new persoon_form(this);
persoon_form1.Show(this);
this.Hide();
break;
}
}
else
{
Global.return_id = index.ToString();
if (pf != null)
{
pf.fill_id();
}
if (pr != null)
{
pr.fill_id();
}
Global.give_return = false;
Close();
}
}
}
}
I found my problem. the column that I wanted clickable is a buttoncolumn, witch I add when loading the grid. but after filter that column doesnt get refresh or get new data so it things i is the first and only column left whilst the other columns get rebuilt. so calling dataGridView1.Columns.Clear(); and recreating the button column after grid is refilld did the trick, –