datagridview only searching first row - c#

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));
}));

Related

How to tick all checkboxes

I have a gridview control on my form.Its first column is checkboxcolumn and the other one textboxcolumn.I am populating Textbox columns with some string values coming from list
like this way
for (int i = 0; i < listeList.Count; i++)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[1].Value = listeList[i];
}
What am i trying to do is to select all the checboxes in the gridview once the user click button How can I do this
Here is what I have tried
private void btnselectAll_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
// row.Cells[0].Value = "true";
//if (row.Cells[0].Value != ull)
//{
// if (Convert.ToBoolean(row.Cells[0].Value))
// {
// MessageBox.Show(row.Cells[1].Value.ToString());
// }
//}
}
}
Cast the appropriate cell to DataGridViewCheckBoxCell:
for(int row = 0; row < this.dataGridView1.Rows.Count; row++)
{
var chkCell = dataGridView1[0, row] as DataGridViewCheckBoxCell;
// read:
bool isChecked = (bool)chkCell.EditedFormattedValue;
// assign:
chkCell.Value = true;
}

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;
}
}

Do something if selected Cells are in the same Column

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
}
}
}

Assigning values from a cell to another

int rowsCount = 0;
//This checks to see that both textbox for items and subitems do not gain focus at the same time
if (textBoxSubItems.Text != string.Empty)
txtItems.Enabled = false;
else
txtItems.Enabled = true;
if (comboBoxItems.SelectedItem != null)
{
int idx = dataGridViewTimesheet.Rows.Add();
DataGridViewRow row = dataGridViewTimesheet.Rows[idx];
row.Cells["items"].Value = comboBoxItems.SelectedItem.ToString() + "-" + textBoxSubItems.Text;
row.Cells["fromTime"].Value = DateTime.Now.ToLongTimeString();
row.Cells["toTime"].Value = null;
row.Cells["duration"].Value = null;
row.Cells["subTotal"].Value = null;
// row.Cells["comments"].Value = "1";
}
else
MessageBox.Show("Please select an item");
string strGetColumnValue;
if (dataGridViewTimesheet.Rows.Count != 0)
rowsCount = dataGridViewTimesheet.Rows.Count;
else
MessageBox.Show("No row in the datagridview");
while (dataGridViewTimesheet.Rows.Count > 0)
{
try
{
if (dataGridViewTimesheet.CurrentRow != null)
for (int counter = 0; counter < dataGridViewTimesheet.Columns.Count; counter++)
{
if (dataGridViewTimesheet.Columns[counter].Index == 3)
{
strGetColumnValue = dataGridViewTimesheet.Rows[rowsCount].Cells[counter].Value.ToString();
dataGridViewTimesheet.Rows[rowsCount - 1].Cells[3].Value = strGetColumnValue;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Please i have 6 columns in a datagridview, the rows are added dynamically. What i want is when rows are more than one in the datagridview it should assign the value of the second column on the current(the last row created) row to the third column of the previous row. How do I achieve this.
Try this kind of thing
int count =1;
foreach (DataGridRow row in dataGridViewTimesheet.Rows)
{
if (count % 2 == 0)
{
string secondColumn = dataGridViewTimesheet.Rows[count -1].Cells[1].ToString();
dataGridViewTimesheet.Rows[count].Cells[2].Value = secondColumn;
}
count++;
}

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");
}

Categories

Resources