set Tag property datagridview C# - c#

I'm creating a datagridview in WinForms. Each cell in the datagridview is either a textboxcell or datagridview image cell. I'm firing a cellMouseDownEent( object sender, DataGridViewCellMouseEventArgs e). If the sected cell is a image cell I perform task1 and if it is textboxcell I perform task2. I'm not getting how to find out whether the current cell is image cell or text box cell. I tried setting tag property of image cell to 0 and textboxcell cell to 1 to identify which is being clicked, but no luck. Any advice is aapreciated.
Thanks,
I'm adding my code here:
Ignore if a column or row header is clicked
if (e.RowIndex != -1 && e.ColumnIndex != -1)
{
if (e.Button == MouseButtons.Right)
{
DataGridViewCell clickedCell = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];
// Here you can do whatever you want with the cell
this.dgvAddFilters.CurrentCell = clickedCell; // Select the clicked cell, for instance
// Get mouse position relative to the vehicles grid
var relativeMousePosition = dgvAddFilters.PointToClient(Cursor.Position);
if (clickedCell.Tag.ToString()==null)
{
return;
}
else if (imageCell == null) return;
else if (e.ColumnIndex == 0 && e.RowIndex == 0)
{
if ((dgvAddFilters[e.ColumnIndex, e.RowIndex + 2].Value == null))
// (dgvAddFilters[e.ColumnIndex + 2, e.RowIndex].Value == null))
{
dgvAddFilters.ContextMenuStrip = contMenuOr;
this.contMenuOr.Show(dgvAddFilters, relativeMousePosition);
}
else return;
}
else if ((e.ColumnIndex == 0)
&& (e.RowIndex > 0)
&& (dgvAddFilters[e.ColumnIndex + 2, e.RowIndex].Value == null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex + 2].Value == null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex].Value != null))
{
dgvAddFilters.ContextMenuStrip = contMenuFilterMenu;
this.contMenuFilterMenu.Show(dgvAddFilters, relativeMousePosition);
}
else if ((e.ColumnIndex == 0)
&& (e.RowIndex > 0)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex + 2].Value == null)
&& (dgvAddFilters[e.ColumnIndex + 2, e.RowIndex].Value != null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex].Value != null))
{
dgvAddFilters.ContextMenuStrip = contMenuOrEditDelete;
this.contMenuOrEditDelete.Show(dgvAddFilters, relativeMousePosition);
}
else if ((e.ColumnIndex == 0)
&& (e.RowIndex > 0)
&& (dgvAddFilters[e.ColumnIndex + 2, e.RowIndex].Value == null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex + 2].Value != null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex].Value != null))
{
dgvAddFilters.ContextMenuStrip = contMenuAndDeleteEditMenu;
this.contMenuAndDeleteEditMenu.Show(dgvAddFilters, relativeMousePosition);
}
else if ((dgvAddFilters[e.ColumnIndex, (e.RowIndex + 2)] != null)
&& (dgvAddFilters[(e.ColumnIndex + 2), e.RowIndex].Value != null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex].Value != null))
{
dgvAddFilters.ContextMenuStrip = contmenuDeletEdit;
this.contmenuDeletEdit.Show(dgvAddFilters, relativeMousePosition);
}
else if ((dgvAddFilters[e.ColumnIndex, (e.RowIndex + 2)] != null)
&& (dgvAddFilters[e.ColumnIndex, e.RowIndex].Value != null))
{
dgvAddFilters.ContextMenuStrip = contMenuAndDeleteEditMenu;
this.contMenuAndDeleteEditMenu.Show(dgvAddFilters, relativeMousePosition);
}
else
{
return;
}

To know the type of cell that is clicked, You can try below way of doing.... See if it is helpful.
Get the clicked cell and check for its type.
Below is an example to check for checkbox type cell.
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
Type type = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].GetType();
if (type.Name == "DataGridViewCheckBoxCell")
{
string value = (string)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
}
}

Does this help you?
using System.ComponentModel;
using System.Windows.Forms;
namespace DGVCellTypes_47599159
{
public partial class Form1 : Form
{
DataGridView dgv = new DataGridView();
BindingList<dgventry> dgventries = new BindingList<dgventry>();
public Form1()
{
InitializeComponent();
InitOurStuff();
}
private void InitOurStuff()
{
this.Controls.Add(dgv);
dgv.Dock = DockStyle.Top;
dgv.DataSource = dgventries;
dgv.CellMouseDown += Dgv_CellMouseDown;
for (int i = 0; i < 10; i++)
{
dgventries.Add(new dgventry { col1 = $"col1_{i}", col2 = $"col2_{i}", col3 = (i % 2) > 0 });
}
}
private void Dgv_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewCheckBoxCell)
{
//do something
}
else if (dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewTextBoxCell)
{
//do something
}
else if (dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewImageCell)
{
//do something
}
else
{
//do something
}
}
}
public class dgventry
{
public string col1 { get; set; }
public string col2 { get; set; }
public bool col3 { get; set; }
}
}
I'm not getting how to find out whether the current cell is image cell or text box cell
private void Dgv_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewCheckBoxCell)
{
//do something
}
else if (dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewTextBoxCell)
{
//do something
}
else if (dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewImageCell)
{
//do something
}
else
{
//do something
}
}

Related

Change row color in datagridview

I know it's already been written about.
Everything looks very good. But when I move to the right to see the rest of the columns, the rows in DataDridView start blinking very much. I can't solve this.
private void registersDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridViewRow rowDataGridView = null;
string dataPropertyName;
dataPropertyName = this.registersDataGridView.Columns[e.ColumnIndex].DataPropertyName;
int isApprovedColumnIndex = this.registersDataGridView.Columns[isApprovedColumnName].Index;
int isCancelledColumnIndex = this.registersDataGridView.Columns[isCancelledColumnName].Index;
bool theColorHasBeenSet = false;
if (e.RowIndex >= 0 && e.RowIndex != btregisterDgvRowIndex)
{
rowDataGridView = this.registersDataGridView.Rows[e.RowIndex];
if (this.registersDataGridView.Columns[isCancelledColumnIndex].DataPropertyName == "IsCancelled")
{
if (rowDataGridView.Cells[isCancelledColumnIndex].Value != null && rowDataGridView.Cells[isCancelledColumnIndex].Value.ToString() == "Tak")
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.PaleVioletRed)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.PaleVioletRed;
}
theColorHasBeenSet = true;
}
else
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.Ivory)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.Ivory;
}
}
btregisterDgvRowIndex = e.RowIndex;
}
if (this.registersDataGridView.Columns[isApprovedColumnIndex].DataPropertyName == "IsApproved")
{
if (!theColorHasBeenSet)
{
if (rowDataGridView.Cells[isApprovedColumnName].Value != null && rowDataGridView.Cells[isApprovedColumnName].Value.ToString() == "-")
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.LightGray)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.LightGray;
}
theColorHasBeenSet = true;
}
else if (rowDataGridView.Cells[isApprovedColumnName].Value != null && rowDataGridView.Cells[isApprovedColumnName].Value.ToString() == "Nie")
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.PaleVioletRed)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.PaleVioletRed;
}
theColorHasBeenSet = true;
}
else
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.Ivory)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.Ivory;
}
}
btregisterDgvRowIndex = e.RowIndex;
}
}
}
}
else
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.Ivory)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.Ivory;
}
}
You're not setting the theColorHasBeenSet here which might cause it to change between Ivory and the next color on your list.
Your code seems to verbose to me, try the following
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex < 0)
return;
var rowDataGridView = this.registersDataGridView.Rows[e.RowIndex];
Color GetBackgroundColor()
{
var isApprovedColumnIndex = this.registersDataGridView.Columns[isApprovedColumnName].Index;
var isCancelledColumnIndex = this.registersDataGridView.Columns[isCancelledColumnName].Index;
if (this.registersDataGridView.Columns[isCancelledColumnIndex].DataPropertyName == "IsCancelled")
{
var strValue = Convert.ToString(rowDataGridView.Cells[isCancelledColumnIndex].Value);
if (strValue == "Tak")
return Color.PaleVioletRed;
}
if (this.registersDataGridView.Columns[isApprovedColumnIndex].DataPropertyName == "IsApproved")
{
var strValue = Convert.ToString(rowDataGridView.Cells[isApprovedColumnIndex].Value);
if (strValue == "-")
return Color.LightGray;
if (strValue == "Nie")
return Color.PaleVioletRed;
}
return Color.Ivory;
}
rowDataGridView.DefaultCellStyle.BackColor = GetBackgroundColor();
}

Get value of checkbox in Datagridview?

I tried to get value of checked checkbox in DataGridView, so I check if value is true or false:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex != -1)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if ((bool)dataGridView1.Rows[i].Cells["check"].Value == true)
{
dataGridView1.Rows[i].Cells["check"].Value = false;
}
else
{
dataGridView1.Rows[i].Cells["check"].Value = true;
}
button2.Enabled = (counter > 0);
}
}
}
}
It involks an error in line:
if ((bool)dataGridView1.Rows[i].Cells["check"].Value == true)
Second solution:
if (dataGridView1.Rows[i].Cells["check"].Value == null || (bool)dataGridView1.Rows[i].Cells["check"].Value == false)
{
dataGridView1.Rows[i].Cells["check"].Value = true;
counter++;
}
else
{
dataGridView1.Rows[i].Cells["check"].Value = false;
counter--;
}
The code below works, but sometimes checkbox is not checked
I am doing something really similar in a project of mine,
I am only using OnCellValueChanged instead of CellContentClick.
Here's my working line of code
bool completed = Convert.ToBoolean(dgv.Rows[e.RowIndex].Cells[1].Value.ToString());
What is exactly your error? Did you try to see what .Value was in the debugger ?

checkbox only one allowed, code not working [duplicate]

This question already has answers here:
Only one checkbox to be selected
(6 answers)
Closed 6 years ago.
I am struggling with why my code is not working. This is for a school assignment. I am allowed to ask for help. I am new to programming. I am using visual studio 2015. I am trying to get it so the user must only be allowed to select one checkbox. I have other checkboxes in this assignment so using last checked will not work. I am not getting errors, it just does nothing. Thanks!
My checkBoxes are named checkBox1, checkBox2,......5
My entire current code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Chapter6Homework
{
public partial class IceCreamOrder : Form
{
public IceCreamOrder()
{
InitializeComponent();
}
private void btn_Clear_Click(object sender, EventArgs e)
{
// Clear flavors by automatically selecting default button on Clear button click
rdbDefault.Checked = true;
// Clear toppings
checkBox_CookieDough.CheckState = CheckState.Unchecked;
checkBox_ChocolateSyrup.CheckState = CheckState.Unchecked;
checkBox_Marshmallows.CheckState = CheckState.Unchecked;
checkBox_OreoPieces.CheckState = CheckState.Unchecked;
checkbox_Sprinkles.CheckState = CheckState.Unchecked;
checkbox_Walnuts.CheckState = CheckState.Unchecked;
// Clear List Box
lstDisplay.Items.Clear();
// Clear scoops
checkBox1.CheckState = CheckState.Unchecked;
checkBox2.CheckState = CheckState.Unchecked;
checkBox3.CheckState = CheckState.Unchecked;
checkBox4.CheckState = CheckState.Unchecked;
checkBox5.CheckState = CheckState.Unchecked;
}
private void btn_CalculateCost_Click(object sender, EventArgs e)
{
// Verify user selected a flavor
if (rdbDefault.Checked == true)
{
MessageBox.Show("Please select a flavor");
return;
}
// Verify user seleted # of scoops
if (checkBox1.CheckState == CheckState.Unchecked &&
checkBox2.CheckState == CheckState.Unchecked &&
checkBox3.CheckState == CheckState.Unchecked &&
checkBox4.CheckState == CheckState.Unchecked &&
checkBox5.CheckState == CheckState.Unchecked)
{
MessageBox.Show("You must select a number of scoops. 1 is a must but 5 is recommended!");
return;
}
//Verify user got the toppings they wanted if any
if (checkBox_ChocolateSyrup.CheckState == CheckState.Unchecked &&
checkBox_CookieDough.CheckState == CheckState.Unchecked &&
checkBox_Marshmallows.CheckState == CheckState.Unchecked &&
checkBox_OreoPieces.CheckState == CheckState.Unchecked &&
checkbox_Sprinkles.CheckState == CheckState.Unchecked &&
checkbox_Walnuts.CheckState == CheckState.Unchecked)
{
DialogResult dr = MessageBox.Show("Are you sure you don't want toppings?",
"help", MessageBoxButtons.YesNo);
switch (dr)
{
case DialogResult.Yes: break;
case DialogResult.No: return;
}
}
// Declare Variables and constants
double flavorCost = FlavorCost();
double toppingCost = ToppingCost();
double scoops = Scoops() * flavorCost;
double subTotal = (flavorCost + toppingCost + scoops);
double salesTax = subTotal * .08;
double total = subTotal + salesTax;
// Display total price of order
lstDisplay.Items.Clear();
lstDisplay.Items.Add("Total: " + total.ToString("C2"));
// Display total sales tax
lstDisplay.Items.Add("");
lstDisplay.Items.Add("Sales Tax: " + salesTax.ToString("C2"));
// Display Flavor Cost
lstDisplay.Items.Add("Flavor: " + flavorCost.ToString("C2"));
// Display Scoops Cost
lstDisplay.Items.Add("Scoops: " + scoops.ToString("C2"));
// Display Toppings
lstDisplay.Items.Add("Toppings: " + toppingCost.ToString("C2"));
}
// Get flavor cost
Double FlavorCost()
{
if ((radioButton_Chocolate.Checked == true) || (radioButton_Strawberry.Checked == true))
return 1.5F;
else if (radioButton_Vanilla.Checked == true)
return 1.25F;
else
return 0;
}
// Get num of scoops
Double Scoops()
{
if (checkBox1.Checked == true)
return 1;
else if (checkBox2.Checked == true)
return 2;
else if (checkBox3.Checked == true)
return 3;
else if (checkBox4.Checked == true)
return 4;
else if (checkBox5.Checked == true)
return 5;
else
return 0;
}
// Get Toppings
Double ToppingCost()
{
if ((checkBox_ChocolateSyrup.Checked == true) ||
(checkBox_Marshmallows.Checked == true) ||
(checkbox_Sprinkles.Checked == true))
return .25F;
else if ((checkBox_OreoPieces.Checked == true) ||
(checkBox_CookieDough.Checked == true) ||
(checkbox_Walnuts.Checked == true))
return .50F;
else
return 0;
}
private void IceCreamOrder_Load_1(object sender, EventArgs e)
{
//Set Default to true on load
rdbDefault.Checked = true;
}
internal class Sub
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
int numberChecked = 0;
CheckBox[] array = new
CheckBox[] { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5 };
for (int i = 0; i < array.Length; i++)
{
if
(array[i].Checked)
numberChecked++;
else if
(numberChecked > 1)
MessageBox.Show("You have checked "
+ numberChecked.ToString() + " checkBoxes. Only one is allowed.");
else
return;
}
}
}
}
Use RadioButton with grouping.
To make your solution work: ( sender is the selected checkbox )
private void checkBox1_Checked(object sender, EventArgs e)
{
var array = new CheckBox[] { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5 };
foreach(var checkbox in array)
{
if(checkbox != sender){
checkbox.IsChecked = false
}
}

How can I color rows in datagridview with condition C#

I want with a condition :
all rows have bool_badge =0 : color with RED
all rows have bool_badge=1 : color with ForestGreen
I have a code Correct BUT just when i click for a cell specific
My code:
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
int row = this.dataGridView1.CurrentCell.RowIndex;
string valeur = dataGridView1[2, row].Value.ToString();
if (valeur == "0")
{
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red;
}
else
{
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.ForestGreen;
}
}
The Result :
1) `
2)
But I want when i execute my application , the test begin if bool_badge 0 or 1, and i have for all the gridview : color RED or ForestGreen ,
I try this code:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string valeur = dataGridView1[2, i].Value.ToString();
if (valeur == "0")
{
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red;
}
else
{
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.ForestGreen;
}
}
But i have ERROR!
this is :
How can i fix it?
Very thanks,
You can use Datagridview's Cell_Formatting event.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].HeaderText == "bool_badge" && dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
// if the column is bool_badge and check null value for the extra row at dgv
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "0")
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
}
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "1")
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.ForestGreen;
}
}
}
Result will be,
Hope helps,
You should use .Rows and .Cells properties.
string valeur = dataGridView1.Rows[i].Cells[2].Value.ToString();
For helping you debugging don't do Value.ToString(); just
var value = dataGridView_XXX.Rows[rowNumber].Cells[i].value;
And
if (value == null) display your row/column index
else dataGridView_XXX.Rows[rowNumber].DefaultCellStyle.BackColor = xxx;

repeater item give me null value

I have button to provide voting functionality. I use a usercontrol.
I get the following exception:
object reference is null
Here is the code
protected void btnVot_Click(object sender, EventArgs e)
{
try
{
//Save Data
sqlCon = DBConnection.GetConnection(string.Empty);
if (sqlCon != null)
{
foreach (RepeaterItem item in rpAnswers.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
VotingAnswers AnswerObj = (VotingAnswers )item.DataItem;
HtmlInputRadioButton rbMyRadio = (HtmlInputRadioButton)item.FindControl("rbMyRadio");
if (rbMyRadio != null && rbMyRadio.Checked)
{
VotAns.AnswerCount = +1;
VotAns.AnswerRatio = (VotAns.AnswerCount * 100) / 100;
if (VotAnswerDAO.Update(sqlCon, VotAns))
{
divQuestion.Visible = false;
divVoting.Visible = true;
}
}
}
}
}
}
catch (Exception)
{
}
finally
{
if (sqlCon != null)
{
sqlCon.Close();
sqlCon.Dispose();
}
}
VotingAnswers AnswerObj = (VotingAnswers )item.DataItem; //is giving me null
Could you please help me understand what is wrong?
Just add condition over there
if(item != null && item.DataItem != null)
{
// Do code....
}
This is not proper solution but it's now helpful for you
I did some refactoring in your code:
protected void btnVot_Click(object sender, EventArgs e)
{
try
{
//Save Data
sqlCon = DBConnection.GetConnection(string.Empty);
if (sqlCon == null)
return;
foreach (RepeaterItem item in rpAnswers.Items)
{
if (item.ItemType != ListItemType.Item && item.ItemType != ListItemType.AlternatingItem)
continue;
VotingAnswers AnswerObj = (VotingAnswers )item.DataItem;
HtmlInputRadioButton rbMyRadio = (HtmlInputRadioButton)item.FindControl("rbMyRadio");
if (rbMyRadio == null || !rbMyRadio.Checked)
continue;
VotAns.AnswerCount = +1;
VotAns.AnswerRatio = (VotAns.AnswerCount * 100) / 100;
if (VotAnswerDAO.Update(sqlCon, VotAns))
{
divQuestion.Visible = false;
divVoting.Visible = true;
}
}
VotingAnswers AnswerObj = (VotingAnswers)item.DataItem;
}
catch (Exception ex)
{
//Do some exception handling here
}
finally
{
if (sqlCon != null)
{
sqlCon.Close();
sqlCon.Dispose();
}
}
}
and move the line:
VotingAnswers AnswerObj = (VotingAnswers)item.DataItem;
to a safer position.
To answer your question, if there is no db connection or the event is triggered by a header or footer in your repeater, the exception will be thrown.

Categories