Do something if selected Cells are in the same Column - c#

I want to do something only if selected dgvCells are in the same Column:
foreach (DataGridViewCell c in dgvC.SelectedCells)
if (c.ColumnIndex is the same) // how to say this ?

Seen no reply for sometime, here is my solution, I don't think it optimized enough, but I think it will do the job
int columnIndex = dgvC.SelectedCells[0].ColumnIndex;
bool sameCol = true;
for(int i=0;i<dgvC.SelectedCells.Count;i++)
{
if(dgvC.SelectedCells[i].ColumnIndex != columnIndex)
{
sameCol = false;
break;
}
}
if (sameCol)
{
MessageBox.Show("Same Column");
}
else
{
MessageBox.Show("Not same column");
}
EDIT:
You can also try:
int columnIndex = dgvC.SelectedCells[0].ColumnIndex;
if (dgvC.SelectedCells.Cast<DataGridViewCell>().Any(r => r.ColumnIndex != columnIndex))
{
//Not same
}
else
{
//Same
}

You can use GroupBy to make sure that cells are from the same column
if(dgvC.SelectedCells.Cast<DataGridViewCell>()
.GroupBy(c => c.ColumnIndex).Count() == 1)
{
foreach (DataGridViewCell c in dgvC.SelectedCells)
//your code
}

Something basic like this should work:
Boolean allCells = true;
int colIndex = dgvC.SelectedCells[0].ColumnIndex;
foreach (DataGridViewCell c in dgvC.SelectedCells)
{
if(c.ColumnIndex != colIndex)
{
allCells = false;
}
}
if(allCells)
{
//do stuff here
}

Try this one.
for (int i=0; i < dgvC.SelectedCells.Count; i++ )
{
int currentCellColumnIndex = dgvC.SelectedCells[i].ColumnIndex;
for (int j=i+1; j < dgvC.SelectedCells.Count-1; j++)
{
if(currentCellColumnIndex == dgvC.SelectedCells[j])
{
//Same column
//dgvC.SelectedCells[i] and all dgvC.SelectedCells[j] have same column
}
}
}

Related

datagridview only searching first row

I am trying to search every cell in my datagridview for a value "test". However it is only searching the first row... (i believe it is searching all the columns) Any ideas on how I can fix this?
dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
string searchValue = "test";
int searching = -1;
while (searching < 7)
{
searching++;
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[searching].Value.ToString().Equals(searchValue))
{
row.Cells[searching].Selected = true;
break;
}
}
}
catch (Exception exc)
{
// MessageBox.Show(exc.Message);
}
}
use this snippet.. basically we iterate through every row/column and set its value as selected if we find a match.
dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
string searchValue = "test";
for (int row = 0; row < dataGridView1.Rows.Count; ++row)
{
for (int col = 0; col < dataGridView1.Columns.Count; ++col)
{
var cellValue = dataGridView1.Rows[row].Cells[col].Value;
if (cellValue != null && cellValue.ToString().Equals(searchValue))
{
dataGridView1.Rows[row].Cells[col].Selected = true;
// if you want to search every cell for the searchValue then you shouldn't break.
// break;
}
}
}
you can also do the above as follows, using concise LINQ code:
dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
string searchValue = "test";
dataGridView1.Rows.ToList().ForEach(row => row.Cells.ToList().ForEach(cell =>
{
cell.Selected = (cell.Value != null && cell.Value.ToString().Equals(searchValue));
}));

How to do the color for a particular row in a gridview?

I am using two forms,when I am sending the StockID from one form to another form,in the second form there is some data in the gridview,now I wan to do tat is,by using that id I want to highlight the that row only. I want to compare the ID is exists in the gridview or not,if exits the I want to Do the higlighten for that full row.,
if (pc == c)
{
for (int i = 0; i < grid_stock.Rows.Count; i++)
{
grid_stock.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.grid_stock.Rows[i].DefaultCellStyle.BackColor = Color.Red;
break;
}
}
// on load or when refersh data
if (SelectingID != null)
{
for (int i = 0; i < dgvInvoiceList.Rows.Count; i++)
{
BillingGeneral.InvoicesDataSet.InvoiceListRow dr = (BillingGeneral.InvoicesDataSet.InvoiceListRow)((DataRowView)dgvInvoiceList.Rows[i].DataBoundItem).Row;
if (dr.ID == SelectingID.Value)
{
dgvInvoiceList.ClearSelection();
dgvInvoiceList.Rows[i].Selected = true;
SelectingID = null;
break;
}
}
}
If the if condition at the top is meant to check if the IDs match , put that inside of your for loop , like this :
for (int i = 0; i < grid_stock.Rows.Count; i++)
{
if(grid_stock.Rows[i].Cells[stockID_column_index].Value == received_stockID) // Check if the row IDs match here
{
grid_stock.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.grid_stock.Rows[i].DefaultCellStyle.BackColor = Color.Red;
break;
}
}
Replace stockID_column_index with the index of the column where StockID is stored .
Try this,
Give correct column index of StockID in row.Cells[0]
foreach (DataGridViewRow row in grid_stock.Rows)
{
if (row.Cells[0].Value.Equals("StockID"))
{
grid_stock.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
row.DefaultCellStyle.BackColor = Color.Red;
}
}

Removing Selected rows in a datagridview in C#?

I am currently using this code:
foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
dataGridView1.Rows.RemoveAt(item.Index);
}
I have checkmarks down the first column, but with this code, it only get the selected. How do i get the Selected CheckBoxes only to delete with the row?
You want something like
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i]
.Cells[yourCheckBoxColIndex].Value) == true)
{
dataGridView1.Rows.RemoveAt(i);
}
}
I hope this helps.
Try something like this:
foreach(DataGridViewRow row in this.dataGridView1.Rows)
{
var checked = Convert.ToBoolean(row.Cells[0].Value); // Assuming the first column contains the Checkbox
if(checked)
dataGridView1.Rows.RemoveAt(row.Index);
}
It could be something like this... This is an example for listview, however the concept is almost there. Loop through the item and find the checkbox id and remove those selected. Hope this helps.
public void btnDeleteClick(object sender, EventArgs e)
{
// Iterate through the ListViewItem
foreach (ListViewItem row in ListView1.Items)
{
// Access the CheckBox
CheckBox cb = (CheckBox)row.FindControl("cbxID");
if (cb != null && cb.Checked)
{
// ListView1.DataKeys[item.DisplayIndex].Values[0].ToString()
try
{
}
catch (Exception err)
{
}
}
}
}
Try this:
if (dgv.SelectedRows.Count>0)
{
dgv.Rows.RemoveAt(dgv.CurrentRow.Index);
}
int s = 1;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = s - 1; j < dataGridView1.Rows.Count - 1; j++)
{
if (Convert.ToInt32(dataGridView1["Stok", j].Value) < 5)
{ s = j; dataGridView1.Rows.RemoveAt(j); break; }
}
}
dataGridView1.Refresh();

Prevent duplicate records when I save the values into the ComboBox - C#

I have been saving into the ComboBox a value out of the selected column in datagridview with below code.
My question is:How can I prevent duplicate records when I save the values into the ComboBox? How can I do that?
Code:
int ColumnIndex = dgUretimListesi.CurrentCell.ColumnIndex;
CmbAra.Text = "";
for (int i = 0; i < dgUretimListesi.Rows.Count; i++)
{
CmbAra.Items.Add(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString());
}
Please try this
private void dgvServerList_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex == 1)
{
string id = dgvServerList[e.ColumnIndex, e.RowIndex].Value.ToString();
int duplicaterow = 0;
for (int row = 0; row < dgvServerList.Rows.Count; row++)
{
if (row != e.RowIndex && id == dgvServerList[e.ColumnIndex, row].Value.ToString())
{
duplicaterow = row + 1;
MessageBox.Show("Duplicate found in the row: " + duplicaterow);
this.dgvServerList[e.ColumnIndex, e.RowIndex].Value = "";
break;
}
}
}
}
catch
{
}
}
you could first transfer your datagridview items to a dictionary (which guarantees uniqueness) and then transfer that dictionary content to the combobox. or you could check for uniqueness yourself using a 'Contains' method on the combobox. you could even tie the dictionary to the combobox as a source for the combobox items.
Dictionary<string,bool> d = new Dictionary<string,bool>();
int ColumnIndex = dgUretimListesi.CurrentCell.ColumnIndex;
CmbAra.Text = "";
for (int i = 0; i < dgUretimListesi.Rows.Count; i++)
{
d[dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString()] = true;
}
CmbAra.Items.AddRange(d.Keys);
Use a set:
int ColumnIndex = dgUretimListesi.CurrentCell.ColumnIndex;
CmbAra.Text = "";
HashSet<string> set = new HashSet<string>();
for (int i = 0; i < dgUretimListesi.Rows.Count; i++)
{
string s = dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString();
if(!set.Contains(s)) {
CmbAra.Items.Add(s);
set.Add(s);
}
}
by using the following check and then determine to add or not
if(CmbAra.Items.Contains(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString()))
You can use the following code part.
if(!(CmbAra.Items.Contains(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString())))
{
CmbAra.Items.Add(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString());
}
else
{
MessageBox.Show("Value Already exists , not added");
}

Method to Find GridView Column Index by Name

I'm trying to write a small method to loop through and find a GridView Column by its Index, since it can change position based on what might be visible.
Here is what I have so far:
private int GetColumnIndexByName(GridView grid, string name)
{
foreach (DataColumn col in grid.Columns)
{
if (col.ColumnName.ToLower().Trim() == name.ToLower().Trim()) return col.Ordinal;
}
return -1;
}
In this case, DataColumn doesn't appear to be the right type to use, but I'm kind of lost as to what I should be doing here.
I can only use .NET 2.0 / 3.5. I can't use 4.0.
I figured it out, I needed to be using DataControlField and slightly different syntax.
The working version:
private int GetColumnIndexByName(GridView grid, string name)
{
foreach (DataControlField col in grid.Columns)
{
if (col.HeaderText.ToLower().Trim() == name.ToLower().Trim())
{
return grid.Columns.IndexOf(col);
}
}
return -1;
}
I prefer collection iteration but why bother with the overhead of foreach and grid.Columns.IndexOf call in this case? Just iterate through array with an index.
private int GetColumnIndexByName(GridView grid, string name)
{
for(int i = 0; i < grid.Columns.Count; i++)
{
if (grid.Columns[i].HeaderText.ToLower().Trim() == name.ToLower().Trim())
{
return i;
}
}
return -1;
}
Better solution which works for Datafield, SortExpression and headerText.
public static int GetBoundFieldIndexByName(this GridView gv,string name)
{
int index = 0;
bool found = false;
foreach (DataControlField c in gv.Columns)
{
if (c is BoundField)
{
BoundField field = (BoundField)c;
if (name == field.DataField ||
name == field.SortExpression ||
name == field.HeaderText)
{
found = true;
break;
}
}
index++;
}
return found ? index : -1;
}
//Get index of column by header text.
int GetColumnIndexByName(GridViewRow row, string headerText)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if(cell.ContainingField is TemplateField){
if(((TemplateField)cell.ContainingField).HeaderText.Equals(headerText))
{
break;
}
}
if(cell.ContainingField is BoundField){
if (((BoundField)cell.ContainingField).HeaderText.Equals(headerText))
{
break;
}
}
columnIndex++;
}
return columnIndex;
}
In case if you need a column itself and not just its index you can use some Linq magic:
DataControlField col=GridView1.Columns.Cast<DataControlField>().First(c => c.HeaderText == "Column_header")
Here's a VB version
Protected Function GetColumnIndexByHeaderText(grid As GridView, findHeader As String) As Integer
Dim i As Integer = 0
For i = 0 To grid.Columns.Count - 1
If grid.Columns(i).HeaderText.ToLower().Trim() = findHeader.ToLower().Trim() Then
Return i
End If
Next
Return -1
End Function
This way, works for me (.NET Gridview):
private int GetColumnIndexByName(GridView grid, string name)
{
for (int i = 0; i < grid.HeaderRow.Cells.Count; i++)
{
if (grid.HeaderRow.Cells[i].Text.ToLower().Trim() == name.ToLower().Trim())
{
return i;
}
}
return -1;
}

Categories

Resources