How to set default display value for data gridview? - c#

I am using Data Grid View.
I have a list of object lets say.
class abc{
public int i{get;set;}
public long b{get;set;}
}
//in Form Load
List<abc> objList = new List();
listpopulate(); // populate the list.
datgridvew.dtasource = objList;
I want to show "-" where Objabc.i value = 0
and want to show "Good" where Objabc.b = 1000
I tried cell default format but in vain.
Can you please help me out ?

You can use an event for that, like:
DataGridView.CellValueChanged Event
Or use DataGridView.CellFormatting Event like this:
private void DataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv.Columns[e.ColumnIndex].Name == "i" &&
e.RowIndex >= 0 &&
dgv["i", e.RowIndex].Value is int) &&
(((int)dgv["i", e.RowIndex].Value) == 0)
{
e.Value = "-";
e.FormattingApplied = true;
}
}
else if (dgv.Columns[e.ColumnIndex].Name == "b" &&
e.RowIndex >= 0 &&
dgv["b", e.RowIndex].Value is int) &&
(((int)dgv["b", e.RowIndex].Value) == 1000)
{
e.Value = "Good";
e.FormattingApplied = true;
}
}
}

HEre you can do using Jquery on clientside
$(document).ready(function () {
$(".GRIDVIEWCLASSNAME").find("td").each(function () {
if ($(this).text() == "0")
{
$(this).html("-");
}
if ($(this).text() == "1000")
{
$(this).html("Good");
}
});
});

Related

C# Programmatically created datagridview - DataGridViewCheckBoxColumn cellValueChanged check state always returning FALSE

In C#, I cannot get DataGridViewCheckBoxColumn event to work. It always get a FALSE value even though I’ve clicked on the checkbox. The other datagridviews (text and combobox) columns work fine. Here is what I am doing…
OK, so I am dynamically creating datagridviews (DGVs) at runtime in my constructor based on how many tab sheets there are in the tab control which is determined by the number of weeks in any given date range i.e. one DGV per tab page (where you tab page for each week)
for (int i = 0; i < wcNumWeeks; i++)
{
foreach (DataRow dr in wbDatesDT.Rows)
{
if (Convert.ToInt16(dr["tabNo"].ToString()) == i + 1)
{
wcDate = Convert.ToDateTime(dr["wcDate"].ToString());
break;
}
}
weeksTabControl.TabPages.Add(wcDate.ToShortDateString());
weeksTabControl.TabPages[i].AutoScroll = true;
weeksTabControl.TabPages[i].Width = 1500;
weeksTabControl.TabPages[i].Height = 700;
weeksTabControl.TabPages[i].Controls.Add(new DataGridView()
{
Name = "dataGridView" + (i + 1).ToString(),
Dock = DockStyle.Fill,
Width = 1450,
Height = 650,
Anchor = (AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right),
ScrollBars = System.Windows.Forms.ScrollBars.Both,
AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
});
}
Again in the constructor, for each datagridview created I am creating event as follows:
foreach (Control thisControl in weeksTabControl.Controls)
{
if (thisControl.GetType() == typeof(TabPage))
{
foreach (Control dgv in thisControl.Controls)
{
if (dgv.GetType() == typeof(DataGridView))
{
BuildWhiteboardDGV((DataGridView)dgv);
PopulateWhiteboardDGV((DataGridView)dgv);
wbDataGridView = (DataGridView)dgv;
wbDataGridView.CellMouseUp += new DataGridViewCellMouseEventHandler(wbDataGridView_CellMouseUp);
wbDataGridView.CellEndEdit += new DataGridViewCellEventHandler(wbDataGridView_CellEndEdit);
wbDataGridView.CurrentCellDirtyStateChanged += new EventHandler(wbDataGridView_CurrentCellDirtyStateChanged);
wbDataGridView.CellValueChanged += new DataGridViewCellEventHandler(wbDataGridView_CellValueChanged);
}
}
}
}
The events themselves are as follows:
void wbDataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (wbDataGridView.IsCurrentCellDirty)
{
wbDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
 
void wbDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex >= 13 && e.ColumnIndex <= 15)
{
System.Drawing.Point cur = new System.Drawing.Point(e.ColumnIndex, e.RowIndex);
DataGridViewCheckBoxCell curCell = (DataGridViewCheckBoxCell)wbDataGridView[cur.X, cur.Y];
if (curCell.Value != null && (bool)(curCell.Value) == true)
{
MessageBox.Show("TRUE");
}
else if (curCell.Value != null && (bool)(curCell.Value) == false)
{
MessageBox.Show("FALSE");
}
else
{
MessageBox.Show("NULL");
}
}
return;
}
catch (Exception ex )
{
MessageBox.Show("wbDataGridView_CellValueChanged() ERROR - " + ex.Message + " --> " + ex.InnerException.ToString());
return;
}
}
Where am I going wrong?
OK.... I think I've sorted it.
In my CellMouseUp() event, I had not catered for the LEFT button.
Therefore, by now adding that, the CellValueChanged() event works correctly and captures the correct DataGridViewCheckCellColumn check state : TRUE when checked and FALSE when unchecked.
public void wbDataGridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left && e.RowIndex != -1) // added this and it now works
{
this.rowIndex = e.RowIndex;
this.colIndex = e.ColumnIndex;
this.wbDataGridView = (DataGridView)sender;
return;
}
if (e.Button == System.Windows.Forms.MouseButtons.Right && e.RowIndex != -1)
{
this.rowIndex = e.RowIndex;
this.colIndex = e.ColumnIndex;
this.wbDataGridView = (DataGridView)sender;
return;
}
}
Thanks for your comments though. Much appreciated.
Jobs a good un !!!!

DataGridView CellContent Checkbox Change Event

I have a datagridview with 3 columns: invoice id, price and a checkbox.
If checkbox is clicked price becomes 0 for that row. Now that is happening.
But when I uncheck the checkbox price should be as it was. But it is remaining zero. Below is my code for cellcontent click. How can i get previous price if checkbox in unchecked?
private void grvItems_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
DataGridViewRow row = this.grvItems.CurrentRow;
if (e.RowIndex >= 0)
{
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn &&
e.RowIndex >= 0)
{
if (e.ColumnIndex == grvItems.Columns["UnderWarranty"].Index)
{
string returnAmt = lblReturnAmountVal.Text;
bool isCheked = (bool)grvItems.Rows[e.RowIndex].Cells["UnderWarranty"].EditedFormattedValue;
if (isCheked)
{
grvItems.Rows[e.RowIndex].Cells["PRICE"].Value = "0.00";
lblReturnAmountVal.Text = "0.00";
}
else
{
}
grvItems.EndEdit();
}
}
}
}
Have you tried the CheckedChanged event? On Winforms and using checkboxes that should help. Untested code below:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
value = 0;
}
else
{
// whatever other logic should happen
}
}
If you want to revert to the original data value you will need to store it somewhere.
You can always use the cell's Tag property for this:
DataGridViewCell cell = grvItems.Rows[e.RowIndex].Cells["PRICE"];
if (isCheked)
{
cell.Tag = cell.Value;
cell.Value = "0.00";
lblReturnAmountVal.Text = "0.00";
}
else
{
// use your cell's datatype here!! VVV
if (cell.Tag != null) cell.Value = cell.Tag as decimal;
}

No overload for '...' matches delegate 'System.Windows.Forms.ItemCheckEventHandler'

After reading this question, it has become apparent to me that I am writing my event incorrectly. However, I have no idea how I am going to be able to re-write what I have written using Object sender. My event adds the text from selected checkboxes to a two-dimensional list (report), and the order in report must be the same as the order of the selected checkboxes. Also, no more than two checkboxes can be selected at a time. Here is the event:
void checkedListBox_ItemCheck(CheckedListBox chkdlstbx, ItemCheckEventArgs e)
{
int index = Convert.ToInt32(chkdlstbx.Tag);
if ((chkdlstbx.CheckedItems.Count == 0) && (e.CurrentValue == CheckState.Unchecked))
{
Var.report[index].Add(chkdlstbx.Text);
}
if ((chkdlstbx.CheckedItems.Count == 1) && (e.CurrentValue == CheckState.Checked))
{
Var.report[index].RemoveAt(0);
}
if ((chkdlstbx.CheckedItems.Count == 1) && (e.CurrentValue == CheckState.Unchecked))
{
if (chkdlstbx.SelectedIndex < chkdlstbx.CheckedIndices[0])
{
Var.report[index].Insert(0, chkdlstbx.Text);
}
else
{
Var.report[index].Add(chkdlstbx.Text);
}
}
if ((chkdlstbx.CheckedItems.Count == 2) && (e.CurrentValue == CheckState.Checked))
{
if (chkdlstbx.SelectedIndex == chkdlstbx.CheckedIndices[0])
{
Var.report[index].RemoveAt(0);
}
else
{
Var.report[index].RemoveAt(1);
}
}
if ((chkdlstbx.CheckedItems.Count == 2) && (e.CurrentValue == CheckState.Unchecked))
{
e.NewValue = CheckState.Unchecked;
}
updateReport();
}
It is being called by this line:
chkdlstbx.ItemCheck += new ItemCheckEventHandler(checkedListBox_ItemCheck);
If anyone could help me re-write my event using object, that'd be awesome. I'm not really sure how else I would go about solving this problem!
This should suffice:
void checkedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
CheckedListBox chkdlstbx = sender as CheckedListBox;
if (chkdlstbx == null)
{
throw new InvalidArgumentException();
}
....
}

Iterate through specific col in DGVs' & compare the string values

I got 2 datagrid views, First datagrid 1st col or Index 0 & the Second datagrid 1st col or Index 0.
How can i loop through a specific col in the datagridviews and look for the string values,if it matches with the list then go to a function.
My approach is not working. How can i do this?
private void b_calculate_Click(object sender, EventArgs e)
{
List<string> value = new List<String>() { "AE0", "AT1", "AT2", "AT3"};
value = new List<string>(datagridview1.Columns[0].Index);
List<string> value2 = new List<String>() { "BE0", "BT1", "BT2", "BT3"};
value2 = new List<string>(datagridview2.Columns[0].Index);
//First Combination
if((value.ToString() == "AT1" || value.ToString() == "AE0" ||
value.ToString() == "AT2")
&&
(value2.ToString() == "BT1" || value2.ToString() == "BE0"))
{
gottoFunction1();
}
//Second Combination
if((value.ToString() == "AT1" || value.ToString() == "AT2" )
&&
(value2.ToString() == "BT1" || value2.ToString() == "BT2"))
{
gottoFunction2();
}
}
Here's a routine that iterates through all available rows in both DataGridViews and does the processing shown in your method:
private void b_calculate_Click(object sender, EventArgs e)
{
for (var i = 0; i < dataGridView1.RowCount; i++)
{
if (dataGridView2.RowCount <= i)
break;
var cellFromDG1 = dataGridView1.Rows[i].Cells[0];
var cellFromDG2 = dataGridView1.Rows[i].Cells[0];
if (cellFromDG1.Value == null || cellFromDG2.Value == null)
{
// this could be the empty row that allows you to
// enter a new record
continue;
}
var value = cellFromDG1.Value.ToString();
var value2 = cellFromDG2.Value.ToString();
if ((value == "AT1" || value == "AE0" || value == "AT2") &&
(value2 == "BT1" || value2 == "BE0"))
{
gottoFunction1();
}
if ((value == "AT1" || value == "AT2") &&
(value2 == "BT1" || value2 == "BT2"))
{
gottoFunction2();
}
}
}

DataGridView: How to make some cells unselectable?

How can I make some cells in DataGridView unselectable?
By 'unselectable' I mean: It cannot be selected in any way and trying to select it won't unselect any other cell.
I don't mean ReadOnly. My cells already have this property as true.
DataGridView.MultiSelect needs to be false.
Thanks to JYL's answer I wrote a code:
private int selectedCellRow = 0;
private int selectedCellColumn = 0;
private void grid_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
if (e.Cell == null || e.StateChanged != DataGridViewElementStates.Selected)
return;
if (e.Cell.RowIndex == 0 || e.Cell.ColumnIndex == 0 || e.Cell.RowIndex == 1 && e.Cell.ColumnIndex == 1)
{
e.Cell.Selected = false;
grid.Rows[selectedCellRow].Cells[selectedCellColumn].Selected = true;
}
else
{
selectedCellRow = e.Cell.RowIndex;
selectedCellColumn = e.Cell.ColumnIndex;
}
//this was only for seeing what is happening
//this.Text = selectedCellRow + " " + selectedCellColumn;
}
But this leads to StackOverflow. What condition and where I need to put to prevent that?
Added and commented the condition you were asking about.
private int selectedCellRow = 0;
private int selectedCellColumn = 0;
private void grid_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
if (e.Cell == null || e.StateChanged != DataGridViewElementStates.Selected)
return;
//if Cell that changed state is to be selected you don't need to process
//as event caused by 'unselectable' will select it again
if (e.Cell.RowIndex == selectedCellRow && e.Cell.ColumnIndex == selectedCellColumn)
return;
//this condition is necessary if you want to reset your DataGridView
if (!e.Cell.Selected)
return;
if (e.Cell.RowIndex == 0 || e.Cell.ColumnIndex == 0 || e.Cell.RowIndex == 1 && e.Cell.ColumnIndex == 1)
{
e.Cell.Selected = false;
grid.Rows[selectedCellRow].Cells[selectedCellColumn].Selected = true;
}
else
{
selectedCellRow = e.Cell.RowIndex;
selectedCellColumn = e.Cell.ColumnIndex;
}
}
You can use the event "CellStateChanged".
private void DataGridViewXYZ_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
if (e.Cell == null
|| e.StateChanged != DataGridViewElementStates.Selected)
return;
if (! [condition here : can this cell be selectable ?])
e.Cell.Selected = false;
}
EDIT : if you leave the MultiSelect property of gridView to True, you can manage yourself a "single select" gridview with unselectable cells : il the cell is selectable, clear the other selection...
I believe this article may prove useful to you:
http://blog.spencen.com/2009/04/25/readonly-rows-and-cells-in-a-datagrid.aspx
The ReadOnly property can be applied to the entire grid, a column, a row, or an individual cell.

Categories

Resources