I created a dynamic combobox in my DataGridview like this:
string strcmd2 = "Select Food_Name,Food_ID from dbo.TblFood_Food ";
Dt2 = Dbc.seletcmd(strcmd2);
DataGridViewComboBoxColumn ColumnAcc = new DataGridViewComboBoxColumn();
ColumnAcc.DataPropertyName = "combo";
ColumnAcc.HeaderText = "Food";
ColumnAcc.DataSource = Dt2;
ColumnAcc.DisplayMember = "Food_Name";
ColumnAcc.ValueMember = "Food_ID";
DataGridview_Food.Columns.Insert(0,ColumnAcc);
Now I want when user selected an item in combobox, its value emerge in another cell of datagridview. what can i do?
Thanks
try this....
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace App1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//string strcmd2 = "Select Food_Name,Food_ID from dbo.TblFood_Food ";
//Dt2 = Dbc.seletcmd(strcmd2);
//fabricate some data....
List<Food> Foods = new List<Food>();
Foods.Add(new Food() { Food_ID = "0", Food_Name = "NONE" });
Foods.Add(new Food() { Food_ID = "1", Food_Name = "Burger" });
Foods.Add(new Food() { Food_ID = "2", Food_Name = "Fries" });
DataGridViewComboBoxColumn ColumnAcc = new DataGridViewComboBoxColumn();
ColumnAcc.DataPropertyName = "combo";
ColumnAcc.HeaderText = "Food";
ColumnAcc.Name = "Food";
ColumnAcc.DataSource = Foods;
ColumnAcc.DisplayMember = "Food_Name";
ColumnAcc.ValueMember = "Food_ID";
DataGridview_Food.Columns.Insert(0, ColumnAcc);
DataGridview_Food.EditingControlShowing += DataGridview_Food_EditingControlShowing;
}
private void DataGridview_Food_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (((DataGridView)sender).CurrentCell.ColumnIndex == 0)
{
ComboBox cmb = e.Control as ComboBox;
if (cmb != null)
{
// remove the current event handler
cmb.SelectionChangeCommitted -= new EventHandler(cmb_SelectionChanged);
// now re-attach the event handler
cmb.SelectionChangeCommitted += new EventHandler(cmb_SelectionChanged);
}
}
}
private void cmb_SelectionChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
Food selectedFood = (Food)cmb.SelectedItem;
MessageBox.Show(string.Format("You selected item {0} ---> {1}", selectedFood.Food_ID, selectedFood.Food_Name));
}
}
}
class Food
{
public string Food_Name { get; set; }
public string Food_ID { get; set; }
}
One option is to handle the DataGridView.CellEndEdit event. After you select an option from the ComboBox and leave the cell, have it update the desired cell. Let's assume the ComboBox column is indexed at 0 and the desired column to update is column 1:
this.dataGridView1.CellEndEdit += DataGridView1_CellEndEdit;
private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
this.dataGridView1[1, e.RowIndex].Value = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value;
}
}
Now let's imagine you have the following ComboBox items:
{{ Food_Name = "Apple", Food_ID = 1 },
{ Food_Name = "Steak", Food_ID = 2 },
{ Food_Name = "Toast", Food_ID = 3 }}
Having set the ComboBoxColumn.ValueMember = "Food_ID: Choosing Apple will set the other cell value to 1; choosing Steak sets the other cell value to 2; etc. That said, if Food_ID is not the value you want to set in the other cell, then consider Monty's approach using the EditControlShowing event.
Related
The program i have create for "Inventory system". And also i have create GridControl from Devexpress Tools. how do i convert this code to Devexpress gridcontrol..
please refer attached image GridControl
private void dgvinvoicesummary_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
int id = e.RowIndex;
DataGridViewRow row = dgvinvoicesummary.Rows[id];
int ddl1 = Convert.ToInt32(row.Cells[2].Value.ToString());
if (dgvinvoicesummary.Columns[e.ColumnIndex].Name == "Update")
{
invoiceSummary Obj = new invoiceSummary
{
CustomerName = row.Cells["customerName"].Value.ToString(),
InvoiceID = Convert.ToInt32(row.Cells["invoiceId"].Value.ToString()),
IssueDate = row.Cells["issue_date"].Value.ToString(),
DueDate = row.Cells["due_date"].Value.ToString(),
Status = row.Cells["Status"].Value.ToString()
};
frmAddinvoice fm = new frmAddinvoice(Obj);
fm.ShowDialog();
this.Close();
GetInvoiceSummaryData();
}
if (dgvinvoicesummary.Columns[e.ColumnIndex].Name == "delete")
{
DeleteInvoiceSummaryRow(ddl1);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The Answer should be like this
private void gridView1_RowCellClick(object sender, RowCellClickEventArgs e)
{
int id = e.RowHandle;
DataRow row = gridView1.GetDataRow(id);
int ddl1 = Convert.ToInt32(gridView1.GetRowCellValue(id, "invoiceId").ToString());
if (e.Column.Name=="ActionUpdate")
{
invoiceSummary Obj = new invoiceSummary
{
CustomerName = gridView1.GetRowCellValue(id, "customerName").ToString(),
InvoiceID = Convert.ToInt32(gridView1.GetRowCellValue(id,"invoiceId").ToString()),
IssueDate = gridView1.GetRowCellValue(id,"issue_date").ToString(),
DueDate = gridView1.GetRowCellValue(id,"due_date").ToString(),
Status = gridView1.GetRowCellValue(id,"Status").ToString(),
PrivateNote = gridView1.GetRowCellValue(id,"privateNotes").ToString(),
PadiAmount = Convert.ToDouble(gridView1.GetRowCellValue(id,"Amount_Paid").ToString()),
Balance = Convert.ToDouble(gridView1.GetRowCellValue(id,"Balance").ToString()),
PaymentType = gridView1.GetRowCellValue(id,"paymentType").ToString(),
DateOfPayment = gridView1.GetRowCellValue(id,"DateOfPayment").ToString(),
TotalDiscount = Convert.ToDouble(gridView1.GetRowCellValue(id,"TotalDiscount").ToString()),
PackagingAmount = Convert.ToDouble(gridView1.GetRowCellValue(id,"PackagingAmount").ToString()),
CustomerNote = gridView1.GetRowCellValue(id,"CustomerNote").ToString(),
TaxTotalAmount = Convert.ToDouble(gridView1.GetRowCellValue(id,"Tax_Amount").ToString()),
Valuedata = Convert.ToDouble(gridView1.GetRowCellValue(id,"Amount").ToString()),
TotalSubAmount = Convert.ToDouble(gridView1.GetRowCellValue(id,"Total_Amount").ToString()),
};
frmAddinvoice fm = new frmAddinvoice(Obj);
fm.ShowDialog();
this.Close();
GetInvoiceSummaryData();
}
else
{
MessageBox.Show("");
}
}
I want to see whatever I see in my comboboxcell in other cell only for the current row I'm trying something like this with no result:
dataGridView1.Rows[0].Cells[0].Value =
dataGridView1.Rows[0].Cells[1].Value;\\ cell 1 is my comboboxcell
I have a class named with Item to add items in List,
Item class;
public class Item
{
public string Name { get; set; }
public int Id { get; set; }
}
In Form_Load, I loaded datagridview,
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add("test1", "test1");
DataGridViewComboBoxColumn testCol = new DataGridViewComboBoxColumn();
testCol.HeaderText = "comboValues";
dataGridView1.Columns.Add(testCol);
dataGridView1.Columns.Add("test2", "test1");
List<Item> items = new List<Item>();
items.Add(new Item() { Name = "One", Id = 1 });
items.Add(new Item() { Name = "Two", Id = 2 }); // created two Items
var cbo = dataGridView1.Columns[1] as DataGridViewComboBoxColumn; // index of 1 is the comboboxColumn
cbo.DataSource = items; // setting datasource
cbo.ValueMember = "Id";
cbo.DisplayMember = "Name";
dataGridView1.Rows.Add("", items[1].Id, "test1");
dataGridView1.Rows.Add("", items[0].Id, "test2");
dataGridView1.Rows.Add("", items[1].Id, "test3"); // and test rows
}
We need to check which row is the previous one before new selection, so we need to use Row_Leave event.
int previousRowIndex = 0; // a variable to keep the index of row
private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
{
previousRowIndex = e.RowIndex;
}
And the main event is SelectionChanged,
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
dataGridView1.Rows[previousRowIndex].Cells[0].Value = ""; // first set the previous row's first cell value empty string.
DataGridViewComboBoxCell comboCell = dataGridView1.CurrentRow.Cells[1] as DataGridViewComboBoxCell;
dataGridView1.CurrentRow.Cells[0].Value = comboCell.EditedFormattedValue; // then set the first cell's value as the combobox's selected value.
}
Result;
Hope helps,
I have a DataGridView with a ComboBox column.
The ComboBox gets filled with a specific list of names and they are identical for every row in the DataGridView.
After I fill my DataGridView, I would like to do the following:
I want every Combo’s value to be set to the corresponding row’s “Table Columns” value, if exists.
I.e. in the picture above I want the value of the first Combo to be “id” (if it contains an item named “id”), the second to be “firstname”, etc.
If the value is not found, it should not select any value in the ComboBox.
Update: My current code that is not working
private void Mappings_Load(object sender, EventArgs e)
{
dgv.DataSource = tableColumns.Select(x => new { Value = x }).ToList();
dgv.Columns[0].HeaderText = "Table Columns";
DataGridViewComboBoxColumn comboColumn = new DataGridViewComboBoxColumn();
comboColumn.HeaderText = "File Columns";
foreach (var item in fileColumns)
comboColumn.Items.Add(item);
dgv.Columns.Add(comboColumn);
foreach(DataGridViewRow row in dgv.Rows)
{
string tableColumnValue = row.Cells[0].Value.ToString();
row.Cells[0].Value = tableColumnValue;
}
}
Trace the change .. you almost did it
private void Form1_Load(object sender, EventArgs e)
{
string[] tableColumns = new string[] { "A", "B", "C", "D" };
string[] fileColumns = new string[] { "A", "B", "C", "X" };
dgv.DataSource = tableColumns.Select(x => new { Value = x }).ToList();
dgv.Columns[0].HeaderText = "Table Columns";
DataGridViewComboBoxColumn comboColumn = new DataGridViewComboBoxColumn();
comboColumn.HeaderText = "File Columns";
foreach (var item in fileColumns)
comboColumn.Items.Add(item);
dgv.Columns.Add(comboColumn);
foreach (DataGridViewRow row in dgv.Rows)
{
string tableColumnValue = row.Cells[0].Value.ToString();
//Change is here
if (fileColumns.Any(i => i == tableColumnValue))
{
row.Cells[1].Value = tableColumnValue;
}
//end change
}
}
A while ago I did a similar thing:
Recognize which fields are of type enum
For the fiels of type enum, show a ComboBoxin the cell of the DataGridView (containing all the possible values of the enum) instead of the simple text field.
I think you only need to change certain parts of the code to transform it to what you are trying to achieve:
public partial class TableView<CollectionType, ItemType> : Form
{
public TableView(CollectionType elements)
{
InitializeComponent();
// custom:
this.DataGridView.DataSource = elements;
AdaptColumnsToColumnValueType();
}
private void AdaptColumnsToColumnValueType()
{
for (int columnIndex = 0; columnIndex < this.DataGridView.Columns.Count; columnIndex++)
{
var column = (DataGridViewColumn)this.DataGridView.Columns[columnIndex];
if (column.ValueType.IsEnum)
{
ReplaceColumnInDatagridView(
oldColumn: column,
newColumn: CreateComboBoxWithEnums(column));
}
}
}
private void ReplaceColumnInDatagridView(DataGridViewColumn oldColumn, DataGridViewColumn newColumn)
{
int columnIndex = oldColumn.Index;
this.DataGridView.Columns.Remove(oldColumn);
this.DataGridView.Columns.Insert(columnIndex, newColumn);
}
private DataGridViewComboBoxColumn CreateComboBoxWithEnums(DataGridViewColumn replacedEnumColumn)
{
var comboboxColumn = new DataGridViewComboBoxColumn();
comboboxColumn.DataSource = Enum.GetValues(replacedEnumColumn.ValueType);
comboboxColumn.DataPropertyName = replacedEnumColumn.DataPropertyName;
comboboxColumn.Name = replacedEnumColumn.Name;
return comboboxColumn;
}
}
you can use the DataGridViews RowsAdded event.
Edit: cmb is your ComboBoxColumn
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) {
//Check if comboboxcolumn contains the value
if(cmb.Items.Contains(dataGridView1.Rows[e.RowIndex].Cells[0].Value)) {
//Set the value
dataGridView1.Rows[e.RowIndex].Cells["cmb"].Value = dataGridView1.Rows[e.RowIndex].Cells[0].Value;
}
}
I am new to windows application.I have a table in which there are two fields namely,Title and Type.
In Type field i have two values "O" & "T".
Now i have to populate a datagrid with this table Title as first column and in second column depending on the Type field value i have to place a control i.e when Type field will have "O" at that time i have to place a combobox in that column and when it is "T" i have to place a text Box
i have tried a lot and googled a lot but both controls in same column is quite difficult for me as a beginner.
Plz help me with this requirement.
this is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ERP_Ship.App_Code.Fleet_Person;
using ERP_Ship.App_Code.Appraisal;
using ERP_Ship.Forms.Master;
using ERP_Ship.App_Code.Common;
using ERP_Ship.App_Code.Vessel_Hardening_Measures;
namespace ERP_Ship.Forms.Reports
{
public partial class Vessel_Hardening_Measures : Form
{
// ? //
private DataSet ds = new DataSet("myDs");
private DataTable dt = new DataTable("Apprdtl");
//Define controls must be add to data grid.
private Label lblControl = new Label();
private TextBox txtControl = new TextBox();
private ComboBox cboControl = new ComboBox();
//Capture the clicked cell
private DataGrid.HitTestInfo hitTestGrid;
//Control definishion to add to DataGrid
DataGridTableStyle dataGridStyle = new DataGridTableStyle();
DataGridTextBoxColumn dataGridLableTitle = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridLableTitle1 = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridLableTitle2 = new DataGridTextBoxColumn();
//DataGridTextBoxColumn dataGridLable = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridTextBox = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridComboBox = new DataGridTextBoxColumn();
private System.Windows.Forms.DataGrid gv_Appraisal;
#region Form Level Variables
string _strName;
string _strCDCNo;
//DataTable dt = new DataTable();
// OracleConnection con1 = new OracleConnection(ConfigurationManager.ConnectionStrings["MySQLConnection"].ConnectionString.ToString());
I_Common objCommon = new I_Common();
DataTable dt1 = new DataTable("dt1");
#endregion
#region Public Properties
public string SearchName
{
set
{
_strName = value;
}
get
{
return _strName;
}
}
public string SearchCDCNo
{
set
{
_strCDCNo = value;
}
get
{
return _strCDCNo;
}
}
#endregion
public Vessel_Hardening_Measures()
{
InitializeComponent();
InitializeControls();
Load_Year();
//for (int index = 0; index <= gv_Appraisal.Columns.Count - 1; index++)
//{
// gv_Appraisal.Columns[index].DataPropertyName = gv_Appraisal.Columns[index].Name;
//}
//gv_Appraisal.AutoGenerateColumns = false;
}
private void InitializeControls()
{
//label property
lblControl.Cursor = Cursors.Hand;
lblControl.ForeColor = Color.Red;
lblControl.Font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic);
//textbox property
txtControl.Cursor = Cursors.Hand;
txtControl.BackColor = Color.WhiteSmoke;
txtControl.ForeColor = Color.DarkSlateBlue;
txtControl.Font = new Font("Arial", 8, FontStyle.Bold);
//textbox events.
txtControl.TextChanged += new EventHandler(txtTextChanged);
string[] dropdownitems = { "Yes", "No", "Not Applicable" };
//Define and add ComboBox rows, will be added to data grid.
for (int i = 0; i < dropdownitems.Count(); i++)
cboControl.Items.Add(dropdownitems[i]);
//combobox property
cboControl.Cursor = Cursors.Hand;
cboControl.DropDownStyle = ComboBoxStyle.DropDownList;
//combobox events.
cboControl.SelectedIndexChanged += new EventHandler(cboSelectedIndexChanged);
}
private void DesignTableStyle()
{
dataGridStyle.PreferredRowHeight = 24;
dataGridStyle.MappingName = "Apprdtl";
gv_Appraisal.TableStyles.Add(dataGridStyle);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle1);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle2);
dataGridStyle.GridColumnStyles.Add(dataGridTextBox);
//dataGridStyle.GridColumnStyles.Add(dataGridComboBox);
dataGridLableTitle.HeaderText = "vhm_id";
dataGridLableTitle.MappingName = "vhm_id";
dataGridLableTitle.Width = 1;
//dataGridLableTitle.Width = 40;
dataGridLableTitle1.HeaderText = "Title";
dataGridLableTitle1.MappingName = "Title";
dataGridLableTitle1.Width = 150;
dataGridLableTitle2.HeaderText = "Type";
dataGridLableTitle2.MappingName = "Type";
dataGridLableTitle2.Width = 1;
//dataGridLableTitle2.Width = 40;
dataGridTextBox.HeaderText = "TEXTBOX_COL";
dataGridTextBox.MappingName = "TextBox_Col";
dataGridTextBox.Width = 130;
//dataGridComboBox.HeaderText = "COMBOBOX_COL";
//dataGridComboBox.MappingName = "ComboBox_col";
//dataGridComboBox.Width = 130;
}
private void Load_DNF() // DATA NOT FOUND OF CDC NO
{
try
{
using (BL_Vessel_Hardening_Measures obj_vsl_hardening_measures = new BL_Vessel_Hardening_Measures())
{
DataTable dataTable = new DataTable();
ds = obj_vsl_hardening_measures.Get_Vessel_Hardening_Measures();
dt1 = ds.Tables[0];
DataColumn dc = new DataColumn("vhm_id");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
dc = new DataColumn("Title");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
dc = new DataColumn("Type");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
//Create a new column for datatable.
dc = new DataColumn("TextBox_Col", System.Type.GetType("System.String"));
//Add created column to datatable object.
dt.Columns.Add(dc);
DataRow dr;
for (int i = 0; i < dt1.Rows.Count; i++)
{
dr = dt.NewRow();
dr["vhm_id"] = dt1.Rows[i]["vhm_id"];
dr["Title"] = dt1.Rows[i]["Title"];
dr["Type"] = dt1.Rows[i]["Type"];
dr["TextBox_Col"] = "";
//dr["ComboBox_Col"] = "";
dt.Rows.Add(dr);
}
// gv_Appraisal.DataSource = ds.Tables[0];
gv_Appraisal.DataSource = dt;
ds.Tables.Remove("Apprdtl");
ds.Tables.Add(dt);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btn_Close_Click(object sender, EventArgs e)
{
cls_Utility.Close_Pending_Form();
Home objHome = new Home();
I_Common.CloseForm(this.MdiParent, this, objHome);
}
private void Reset_Controls()
{
//txt_CDC_NO.Text = "";
//cmb_Name.SelectedIndex = -1;
}
~Vessel_Hardening_Measures()
{
this.Close();
}
private void Vessel_Hardening_Measures_FormClosed(object sender, FormClosedEventArgs e)
{
cls_Utility.Close_Pending_Form();
}
private void Load_Year()
{
try
{
//ddl_Year.DisplayMember = "Year";
//ddl_Year.ValueMember = "Year";
objCommon.Load_Years(ddl_Year, 1);
//string str_year = "";
//str_year = DateTime.Now.AddYears(-1).Year.ToString();
//ddl_Year.Items.Add(str_year);
//str_year = DateTime.Now.Year.ToString();
//ddl_Year.Items.Add(str_year);
// ddl_Year.SelectedIndex = 1;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Vessel_Hardening_Measures_Load(object sender, EventArgs e)
{
DesignTableStyle();
Load_DNF();
ERP_Ship.App_Code.Common.I_Common.MdiFormTopPanel("Vessel Hardening Measures", "Vessel Hardening Measures", this.MdiParent, true);
//ERP_Ship.App_Code.Common.I_Common.StatusInfoLabel("Double Click the Search Record to View or Edit", "I", this.MdiParent, true);
}
private void gv_Appraisal_MouseUp(object sender, MouseEventArgs e)
{
hitTestGrid = gv_Appraisal.HitTest(e.X, e.Y);
if (hitTestGrid != null)
{
//Which column of datagrid has been clicked.
//switch (hitTestGrid.Column)
//{
if (hitTestGrid.Column == 3)
{
if (gv_Appraisal[gv_Appraisal.CurrentRowIndex, 2].ToString() == "T")
{
dataGridStyle.GridColumnStyles.Clear();
dataGridStyle.GridColumnStyles.Add(dataGridTextBox);
dataGridTextBox.HeaderText = "TEXTBOX_COL";
dataGridTextBox.MappingName = "TextBox_Col";
dataGridTextBox.Width = 130;
//Add texbox control to datagrid.
dataGridTextBox.TextBox.Controls.Add(txtControl);
// txtControl.Text = gv_Appraisal[gv_Appraisal.CurrentRowIndex, 3].ToString();
txtControl.Focus();
}
else if (gv_Appraisal[gv_Appraisal.CurrentRowIndex, 2].ToString() == "O")
{
dataGridStyle.GridColumnStyles.Clear();
dataGridStyle.GridColumnStyles.Add(dataGridComboBox);
dataGridComboBox.HeaderText = "COMBOBOX_COL";
dataGridComboBox.MappingName = "ComboBox_col";
dataGridComboBox.Width = 130;
//Add combobox control to datagrid.
dataGridComboBox.TextBox.Controls.Add(cboControl);
cboControl.Focus();
//for (int i = 0; i < cboControl.Items.Count; i++)
//{
// if (cboControl.Items[i].ToString() == gv_Appraisal[gv_Appraisal.CurrentRowIndex, 3].ToString())
// cboControl.SelectedIndex = i;
//}
}
}
}
}
private void txtTextChanged(object sender, System.EventArgs e)
{
ds.Tables["Apprdtl"].Rows[gv_Appraisal.CurrentRowIndex]["TextBox_Col"] = txtControl.Text;
}
//Combobox selected index changed event.
private void cboSelectedIndexChanged(object sender, System.EventArgs e)
{
ds.Tables["Apprdtl"].Rows[gv_Appraisal.CurrentRowIndex]["TextBox_Col"] = cboControl.Text;
}
}
}
There might be multiple approaches to implement functionality, you are looking for.
I found one sample on this link
Check if approach described there suits to your current requirement needs.
I am new to C#,this is my first project on C# language and my backend is Mysql, I am stuck at a particular point ,I am having a form which is containing a datagridview which is binded with database value,in that i have a column "TNS_Date" It is The Expiration Date of Product ,I want that if the TNS_Date is Greater then the Current Date so the Background Colour of that particular Cell Should Get Red in colured ,How could i do this ,please help me with this
I am using winforms and till now i had tried this
foreach (DataGridViewRow row in TNSFormdgv.Rows)
{
var now = DateTime.Now;
var expirationDate = DateTime.Parse(row.Cells[15].Value.ToString());
var OneMonthBefore = expirationDate.AddDays(-30);
if (now > OneMonthBefore && now < expirationDate)
{
row.DefaultCellStyle.BackColor = Color.Yellow;
}
else if (now > expirationDate)
{
row.DefaultCellStyle.BackColor = Color.Red;
}
}
when i am executing the Project i am getting this Error
Object reference not set to an instance of an object
This is my whole code for that particular form please check it where i am getting wrong
public partial class TNS_Subscription : Form
{
public TNS_Subscription()
{
InitializeComponent();
TNSSubscriptionForm();
}
private void TNSFormBackbtn_Click(object sender, EventArgs e)
{
new Form2().Show();
this.Hide();
}
public void TNSSubscriptionForm()
{
string ConString = "datasource=localhost;port=3306;username=root;password=ajay";
MySqlConnection conDataBase = new MySqlConnection(ConString);
MySqlCommand cmdDatabase = new MySqlCommand("Select acmecmpdetails.Cmp_Number,acmecmpdetails.Cmp_Name,acmecmpdetails.Cmp_AdminId,acmecmpdetails.Cmp_Address1,acmecmpdetails.Cmp_Country1,acmecmpdetails.Cmp_State1,acmecmpdetails.Cmp_City1,acmecmpdetails.Cmp_PostalCode,acmecmpdetails.Contact_Person1,acmecmpdetails.LandLine_Number1,acmecmpdetails.MobileNumber,acmecmpdetails.Cntct_Emailid,acmetally_detail.TallySerial_No,acmetally_detail.Tally_Release,acmetally_detail.Tally_Edition,acmetally_detail.TNS_Date,acmetally_detail.Tally_PrefPartner,acmetally_detail.Tally_accountId from acmesolutionsdatabase.acmecmpdetails INNER JOIN acmesolutionsdatabase.acmetally_detail ON acmesolutionsdatabase.acmecmpdetails.TallySerial_No= acmesolutionsdatabase.acmetally_detail.TallySerial_No;", conDataBase);
try
{
MySqlDataAdapter cddsda = new MySqlDataAdapter();
cddsda.SelectCommand = cmdDatabase;
DataTable dbdataset = new DataTable();
cddsda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
TNSFormdgv.DataSource = bsource;
cddsda.Update(dbdataset);
for(int i=0;i<TNSFormdgv.Rows.Count;i++)
{
if (Convert.ToDateTime(TNSFormdgv.Rows[i].Cells["TNS_Date"].Value.ToString()) > System.DateTime.Now.Date)
{
TNSFormdgv.Rows[i].Cells["TNS_Date"].Style.BackColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Thanks In Advance
You could simply do this:
for(int i=0;i<MyGridView.Rows.Count;i++)
{
if (Convert.ToDateTime(MyGridView.Rows[i].Cells["TNS_Date"].Value.ToString()) > System.DateTime.Now.Date)
{
MyGridView.Rows[i].Cells["TNS_Date"].Style.BackColor = System.Drawing.Color.Red;
}
}
It will change the backcolor of the cell "TNS_Date" if its value is greater than current date.
OR
You can use the index of the column TNS_Date like:
If the index of the column TNS_Date is 3, then:
for(int i=0;i<MyGridView.Rows.Count;i++)
{
if (Convert.ToDateTime(MyGridView.Rows[i].Cells[3].Value.ToString()) > System.DateTime.Now.Date)
{
MyGridView.Rows[i].Cells[3].Style.BackColor = System.Drawing.Color.Red;
}
}
I hope it would solve the problem.
Here's sample that could help:
private void Form2_Load(object sender, EventArgs e)
{
dataGridView1.DataSourceChanged += dataGridView1_DataSourceChanged;
List<MyClass> list = new List<MyClass>();
list.Add(new MyClass { ID = 1, Name = "1", Date = DateTime.Now });
list.Add(new MyClass { ID = 2, Name = "2", Date = DateTime.Now });
list.Add(new MyClass { ID = 3, Name = "3", Date = DateTime.Now });
list.Add(new MyClass { ID = 4, Name = "4", Date = DateTime.Now.AddDays(1) });
dataGridView1.DataSource = list;
}
void dataGridView1_DataSourceChanged(object sender, EventArgs e)
{
// Loop through all the cells where date is in future
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells[2].Value != null) && (DateTime)row.Cells[2].Value > DateTime.Now)
{
row.Cells[2].Style.BackColor = Color.Blue;
}
}
}
I am assuming that it's in Windows Forms as you are using datagridview.
For datagridview you'd be required to iterate through each cell of the grid to find the right cell and set the background colour.
I've created following code to do so.
void loadGrid()
{
DataTable dtData = new DataTable();
dtData.Columns.Add("TNS_Date");
DataRow dRow;
clmDate.DataPropertyName = "TNS_Date";
dRow= dtData.NewRow();
dRow["TNS_Date"] = "20-01-2014";
dtData.Rows.Add(dRow);
dRow = dtData.NewRow();
dRow["TNS_Date"] = "20-02-2014";
dtData.Rows.Add(dRow);
dRow = dtData.NewRow();
dRow["TNS_Date"] = "20-03-2014";
dtData.Rows.Add(dRow);
dgvGrid.DataSource = dtData;
for (int i = 0; i <= dgvGrid.RowCount - 1; ++i)
{
//Finding the right cell to change colour.
if(DateTime.Parse(dgvGrid["TNS_Date", i].Value.ToString()) >= DateTime.Now.Date)
dgvGrid[0, i].Style.BackColor = Color.Bisque;
}
}
If you are using asp.net datagridview then use a template field to do that. You can find more details about template field here : http://msdn.microsoft.com/en-us/library/aa479353.aspx