All select /deselect button - c#

enter image description hereI want to make n 'all select' button in datagridview.
datagirdview has checkbox column.
If I press the Select All button, I can select the entire selection.
If I press the Select All button again, I want to release the entire selection.
I can only Select All, no DeSelect All .
Please help me :(
private void Btn_selectall_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in dataGridView1.Rows)
{
item.Selected = true;
item.Cells[0].Value = true;
}
}

You can invert the values like so
item.Selected = !item.Selected;
item.Cells[0].Value = !item.Cells[0].Value;

You could try something like this:
private void Btn_selectall_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Cast<DataGridViewRow>().All(r => r.Selected))
{
// deselect all
foreach (DataGridViewRow item in dataGridView1.Rows)
{
item.Selected = false;
item.Cells[0].Value = false;
}
}
else
{
// select all
foreach (DataGridViewRow item in dataGridView1.Rows)
{
item.Selected = true;
item.Cells[0].Value = true;
}
}
}

Related

DataGridView C# search gives null

I wanted to create a simple program that looks trough each row of a dataGridView on a specific cell.
I got it to work but if the string that I search for isn't found it gives back null. Which screws it up. Here is the code:
string targetSearch = textBox2.Text;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
foreach(DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0].Value.ToString().Equals(targetSearch))
{
row.Selected = true;
break;
}
}
These solutions works for me.
Sample UI
Validate if the value is null.
private void btnSearch_Click(object sender, EventArgs e)
{
string targetSearch = txtSearch.Text.Trim();
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
foreach(DataGridViewRow row in dataGridView1.Rows) {
if (row.cells[0].value == null)
continue;
if(row.cells[0].value.Tostring().Trim().Equals(targetSearch)) {
row.Selected = true;
break;
}
}
}
Handle the NullReference Exception
private void btnSearch_Click(object sender, EventArgs e)
{
string targetSearch = txtSearch.Text.Trim();
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0].Value.ToString().Equals(targetSearch))
{
row.Selected = true;
break;
}
}
}
catch (NullReferenceException ex) { }
}
You are converting null value to string, which gives System.NullReferenceException.
string targetSearch = textBox2.Text;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
foreach(DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0].Value == null) continue; //add this
if (row.Cells[0].Value.ToString().Equals(targetSearch))
{
row.Selected = true;
break;
}
}
There are two things you can try:
Either Set "AllowUserstoAddRows" to False
or
Put the foreach loop in a Try catch block in order to handle the NullReference exception

Delete a row in DataGridView c# using textbox value

I have created a datagridview that gets all the data from MySQL Workbench database. Below this datagridview, I have created another datagrid with the same columns. For that, I have created a copy function, that on selecting the rows form the first datagridview, copies the selected rows to the second datgrid.
I have then created textboxes that displays the rows that are selected in the second datagridview.
All I want to do now is, get the values from the textboxes, match it in first datagridview, and after clicking on delete button, delete the respected row from first datagridview and respectievely from the database.
I am new to c#, so any help will be appreciated.
Source Code:
namespace panelApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void copy_Click(object sender, EventArgs e)
{
// dataGridView2.Rows.Clear(); (code used if you want to delete previous selections)
foreach (DataGridViewRow item in dataGridView1.Rows)
{
if (item.Selected == true)
{
int n = dataGridView2.Rows.Add();
dataGridView2.Rows[n].Cells[0].Value = item.Cells[0].Value.ToString();
dataGridView2.Rows[n].Cells[1].Value = item.Cells[1].Value.ToString();
dataGridView2.Rows[n].Cells[2].Value = item.Cells[2].Value.ToString();
}
}
}
public void fetch_Click(object sender, EventArgs e)
{
this.productsTableAdapter.Fill(this.productsDataset.products);
productsDataset dt = new productsDataset();
foreach (DataRow item in dt.products.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[1].Value = item["product_id"].ToString();
dataGridView1.Rows[n].Cells[2].Value = item["product_name"].ToString();
dataGridView1.Rows[n].Cells[3].Value = item["category_id"].ToString();
}
}
private void delete_btn_Click(object sender, EventArgs e)
{
try
{
if (dataGridView1.Rows.Cell[0].Text == TextBox1.tex) // error on this line.
{
}
}
catch (System.Exception)
{
MessageBox.Show("Not able to Delete");
}
}
private void dataGridView2_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView2.Rows[e.RowIndex];
product_idTxtbx.Text = row.Cells["product_id"].Value.ToString();
proName_txtbx.Text = row.Cells["product_name"].Value.ToString();
catID_txtbx.Text = row.Cells["category_id"].Value.ToString();
}
}
private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView2.Rows[e.RowIndex];
product_idTxtbx.Text = row.Cells["product_id"].Value.ToString();
proName_txtbx.Text = row.Cells["product_name"].Value.ToString();
catID_txtbx.Text = row.Cells["category_id"].Value.ToString();
}
}
private void delete2_Click(object sender, EventArgs e)
{
// if (dataGridView1.Rows["row.index"].Cells["productidDG"].Value.ToString() == product_idTxtbx.Text)
{
}
}
}
}
On delete button click event btn_OnDelete() find the gridview index then find the all id's by row index.
Then compare each gridview row id to textbox item id
like:
if(GridView1.Rows.Cell[0].Text == TextBox1.tex)
{
// Delete Query here
}
for full solution share code with me.
see here demo link: CRUD Operation link
You should use this code:
<asp:Button ID="delete" runat="server" CommandArgument='<%#Eval("Id") %>' Text="Delete" />
private void delete_btn_Click(object sender, EventArgs e)
{
//incase you need the row index
int rowIndex = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex;
int Prod_Id= Convert.ToInt32(e.CommandArgument);
//followed by your code
try
{
// Then Compare your Id here in this if condition
// if (dataGridView1.Rows.Cell[0].Text == TextBox1.tex
if (Prod_id == Convert.ToInt32(TextBox1.text)) // error on this line.
{
// User Code Here
}
}
catch (System.Exception)
{
MessageBox.Show("Not able to Delete");
}
}
please make your code like below
private void delete_btn_Click(object sender, EventArgs e)
{
try
{
foreach (GridViewRow row in dataGridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
if (row.Cell[0].value == TextBox1.tex)
{
//delete opration here for TextBox1.tex/row.Cell[0].Text(Product_id)
break;
}
}
}
}
catch (System.Exception)
{
MessageBox.Show("Not able to Delete");
}
}

Select/Deselect All checkbox

I have a checkboxlist which gets its items from a sql table and change based on what is selected from a drop down menu. I'm trying to add another checkbox in that list which acts as a select/deselect all box. I've seen a few examples around this site, but nothing seems to work quite right.
Intended Functionality: When box is selected, all the other boxes are selected.
When box is un-selected, all the other boxes are selected.
When box is selected, if another box is then unselected, the select all box is unselected.
C#:
List<ListItem> toBeRemoved = new List<ListItem>();
//removes items when new item from dropdown is selected
for (int i = 1; i < CheckOpenTimesheets.Items.Count; i++)
{
toBeRemoved.Add(CheckOpenTimesheets.Items[i]);
}
for (int i = 0; i < toBeRemoved.Count; i++)
{
CheckOpenTimesheets.Items.Remove(toBeRemoved[i]);
}
lblOpenTimesheets.Text = "";
String sql = "sql statement here";
command.CommandText = sql;
command.Parameters.Add(new SqlParameter("userid", ddlActingAs.SelectedValue.ToString()));
SqlDataReader reader = command.ExecuteReader();
//Adds items to the checkboxlist
while (reader.Read())
{
ListItem item = new ListItem();
item.Text += reader.GetDateTime(0).ToString("MM/dd/yyyy") + " is open";
item.Value = reader["StartDate"].ToString();
CheckOpenTimesheets.Items.Add(item);
}
CheckOpenTimesheets.UpdateAfterCallBack = true;
reader.Close();
What I tried for the selection/deselection:
protected void select_DeselectAll(object sender, System.EventArgs e)
{
if (CheckOpenTimesheets.Items[0].Selected == true)
{
foreach (ListItem item in CheckOpenTimesheets.Items)
{
item.Selected = true;
}
}
else
{
foreach (ListItem item in CheckOpenTimesheets.Items)
{
item.Selected = false;
}
}
}
ASP:
<anthem:CheckBoxList ID="CheckOpenTimesheets" OnSelectedIndexChanged="select_DeselectAll" runat="server" AutoPostBack="true" >
<asp:ListItem Text="Select/Deselect All" />
</anthem:CheckBoxList>
Edit: The problem seems to be the OnSelectedIndexChanged event firing when the checkboxes other than the select all one is selected.
Edit2: Made the select all checkbox separate from the checkboxlist. However, when trying to implement the feature where if a checkbox is unselected when the select all checkbox is checked, the select all checkbox is then deselected BUT all the others don't "deselect". This isn't happening though because the select all checkbox event fires.
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
foreach (ListItem item in CheckOpenTimesheets.Items)
{
item.Selected = chkAll.Checked;
}
}
protected void checkbox_Selected(object sender, EventArgs e)
{
chkAll.CheckedChanged -= chkAll_CheckedChanged;
foreach (ListItem item in CheckOpenTimesheets.Items)
{
if ((item.Selected = false) && (chkAll.Checked = true))
{
chkAll.Checked = false;
}
}
}
It sounds like you understand your issue. The problem comes when you click any other checkbox other than the first one. If the first is not checked and you check another checkbox, your logic is telling all of the other checkboxes to not be checked, including the one you just checked.
One option would be to take the "Select/Deselect All" checkbox out of the CheckBoxList. Let it be its own standalone checkbox.
<asp:CheckBox ID="chkAll" runat="server" Text="Select/Deselect All" OnCheckedChanged="chkAll_CheckedChanged" AutoPostBack="true" />
<anthem:CheckBoxList ID="checkOpenTimesheets" OnSelectedIndexChanged="checkOpenTimesheets_SelectedIndexChanged" runat="server" AutoPostBack="true" >
</anthem:CheckBoxList>
Then your select all event handler would just change them all to be the same.
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
foreach(ListItem item in CheckOpenTimesheets.Items)
{
item.Selected = chkAll.Checked;
}
}
Then also build in functionality where you programatically select or deselect the "Select/Deselect All" checkbox if any in the CheckBoxList change to something other than what all the others are. As explained in this answer, the key here would be to turn off the CheckedChanged event of the select all checkbox, otherwise that event will fire as you have seen.
protected void checkOpenTimesheets_SelectedIndexChanged(object sender, EventArgs e)
{
chkAll.CheckedChanged -= chkAll_CheckedChanged;
CheckBoxList checkOpenTimesheets = (CheckBoxList)sender;
if (allItemsCheckedInCheckBoxList(checkOpenTimesheets))
{
chkAll.Checked = true;
}
else if (allItemsUnCheckedInCheckBoxList(checkOpenTimesheets))
{
chkAll.Checked = false;
}
chkAll.CheckedChanged += chkAll_CheckedChanged;
}
private bool allItemsCheckedInCheckBoxList(CheckBoxList checkBoxList)
{
bool allItemsChecked = true;
foreach (ListItem item in checkBoxList.Items)
{
allItemsChecked = item.Selected;
if (!allItemsChecked)
break;
}
return allItemsChecked;
}
private bool allItemsUnCheckedInCheckBoxList(CheckBoxList checkBoxList)
{
bool allItemsUnChecked = false;
foreach (ListItem item in checkBoxList.Items)
{
allItemsUnChecked = item.Selected;
if (allItemsUnChecked)
break;
}
return allItemsUnChecked;
}

how can i extract the index of subitems in a listview?

im trying to pass an item from a listview1 to another listview2 and i want to check if the selected item is still not present in listview2. im trying to use a for loop to get each index of listview2 and compare it to the item selected in listview1. i tried using this but an error says that value of 0 is not a valid index.
private void listView1_DoubleClick(object sender, EventArgs e)
{
bool test = true;
for (int i = 0; i < listView1.Items.Count; i++)
{
string ls = listView2.Items[i].SubItems[0].Text;
string ps = listView1.Items[listView1.FocusedItem.Index].SubItems[0].Text;
if (ls.Trim() == ps.Trim())
{
test = false;
}
}
if (test == true)
{
ListViewItem ty = new ListViewItem(listView1.Items[listView1.FocusedItem.Index].SubItems[0].Text);
ty.SubItems.Add(listView1.Items[listView1.FocusedItem.Index].SubItems[1].Text);
listView2.Items.AddRange(new ListViewItem[] { ty });
}
else
{
MessageBox.Show("Student is already present in the list.","Cannot add to list",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
}
figured it out just as suggested. i used the foreach statement
private void listView1_DoubleClick(object sender, EventArgs e)
{
bool test = true;
string ps = listView1.Items[listView1.FocusedItem.Index].SubItems[0].Text;
foreach(ListViewItem disitem in listView2.Items)
{
string ls = disitem.SubItems[0].Text;
if (ps.Trim() == ls.Trim())
{
test = false;
}}
if (test == true)
{
ListViewItem ty = new ListViewItem(listView1.Items[listView1.FocusedItem.Index].SubItems[0].Text); ty.SubItems.Add(listView1.Items[listView1.FocusedItem.Index].SubItems[1].Text);
listView2.Items.AddRange(new ListViewItem[] { ty });
}
else
{
MessageBox.Show("Student is already present in the list.","Cannot add to list",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}}
I'm trying to pass an item from a listview1 to another listview2 and I
want to check if the selected item is still not present in listview2.
I would simplify your method to something like:
private void listView1_DoubleClick(object sender, EventArgs e)
{
// Get the value of the selected item
string theItem = listView1.SelectedItems[0];
// Add to second list if it's not already in there
if(!listView2.Items.Contains(theItem))
{
listView2.Items.Add(theItem);
}
else
{
MessageBox.Show("Student is already present in the list.","Cannot add to list",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
}
private void listView1_DoubleClick(object sender, EventArgs e)
{
bool test = true;
var selectedItem = listView1.SelectedItems[0];
foreach(var item in listview2.Items)
{
string listview2Text = item.SubItems[0].Text;
string listview1Text = selectedItem.SubItems[0].Text;
if (listview2Text.Trim() == listview1Text.Trim())
{
test = false;
}
}
if (test == true)
{
//I am not sure exactly what you're trying to do if the test is true but I think you're trying to do this
listView2.Items.Add(selectedItem);
}
else
{
MessageBox.Show("Student is already present in the list.","Cannot add to list",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
}
I believe it should be something like:
private void listView1_DoubleClick(object sender, EventArgs e)
{
bool add = true;
string selected = listView1.Items[listView1.FocusedItem.Index];
foreach(ListViewItem item in listView2.Items)
if (selected.SubItems[0].Text == item.SubItems[0].Text)
{
add = false;
break;
}
if(add)
listView2.Items.Add(selected);
else
MessageBox.Show("Student is already present in the list.","Cannot add to list",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
but I am pretty unsure...

How to loop through dropdown items in a toolstrip

I have a dropdown in my toolstrip (toolbar) i have attached a click event to each item in drop down as the dropdown has been populated dynamically, now i can casted the selected item in the dropdown and set its state to checked, to have a tick next to it, i wish to have a loop in another method to check which item has been checked. How do i loop through the items in the dropdown checking which item is checked?
foreach (DataSet1.xspLibraryByNameRow libName in data.xspLibraryByName)
{
var name = new LibraryItems(libName);
if (libName.xlib_Code != "NULL")
{
catDrpDwn.DropDown.Items.Add(name);
catDrpDwn.DropDown.Tag = name;
name.Click += new EventHandler(name_Click);
}
}
}
void mapArea_VE_MapReady(object sender, EventArgs e)
{
loadPoints();
}
void name_Click(object sender, EventArgs e)
{
var selected = (LibraryItems)sender;
selected.Checked = true;
loadPoints();
}
foreach (var items in catDrpDwn.DropDown.Items)
{
var it = (LibraryItems)items;
if (it.Checked == true)
{
}
}
Try this
var items=catDrpDwn.DropDown.Items.Cast<LibraryItems>().Where(d=>d.Checked).ToList();
here you will get all checked items and you can loop into it.

Categories

Resources