I have this code to fill my datagridview from my database.
string query = "SELECT * From guestinfo";
using (con)
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, con))
{
using (DataTable dt = new DataTable())
{
adapter.Fill(dt);
dataGridView1.AutoGenerateColumns = false;
dataGridView1.ColumnCount = 4;
dataGridView1.Columns[0].Name = "RoomNumber";
dataGridView1.Columns[0].HeaderText = "Room Number";
dataGridView1.Columns[0].DataPropertyName= "RoomNumber";
dataGridView1.Columns[1].Name = "GuestName";
dataGridView1.Columns[1].HeaderText = "Guest Name";
dataGridView1.Columns[1].DataPropertyName = "GuestName";
dataGridView1.Columns[2].Name = "RoomType";
dataGridView1.Columns[2].HeaderText = "Room Type";
dataGridView1.Columns[2].DataPropertyName = "RoomType";
dataGridView1.Columns[3].Name = "Status";
dataGridView1.Columns[3].HeaderText = "Status";
dataGridView1.Columns[3].DataPropertyName = "Status";
dataGridView1.DataSource = dt;
dataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders);}}}
And this code to remove the rows with empty value.
for (int i = dataGridView1.Rows.Count - 1; i >= 0; i--)
{
DataGridViewRow dataGridViewRow = dataGridView1.Rows[i];
foreach (DataGridViewCell cell in dataGridViewRow.Cells)
{
string val = cell.Value as string;
if (string.IsNullOrEmpty(val))
{
if (!dataGridViewRow.IsNewRow)
{
dataGridView1.Rows.Remove(dataGridViewRow);
break;
}
}
}
}
This Codes works but when I Add This code some runtime error happened.It Removes all my data. Even it is not empty.
dataGridView1.Columns[4].Name = "CheckDate";
dataGridView1.Columns[4].HeaderText = "Check Date";
dataGridView1.Columns[4].DataPropertyName = "CheckDate";
dataGridView1.Columns[5].Name = "OutDate";
dataGridView1.Columns[5].HeaderText = "Out Date";
dataGridView1.Columns[5].DataPropertyName = "OutDate";
Related
I'm going to need help with this one. Been 2 days now without figuring out the root case.
In my application I add a set number of rows to a DataTable and display it through a DataGrid.
A timer is set to do some work on a interval (currently set to 10 seconds):
Iterate row by row on the DataTable.
Get the hostname from the column "hostname"
Ping the computer
If pingresult == success continue the operation and send a Windows Toast Message.
Adding the list of the computers to the DataTable and displaying them into DataGrid works fine.
The problem occurs after I hit the Start button which triggers the timer. The amount of time it takes before the error occurs depends on how many rows are added to the DataTable.
Sorry for all the info posted below here. The frustration has kicked in for me. Hopefully someone can spot the obvious and help me get passed this problem. I have commented out some of the code to narrow the where the problem is located.
For testing purposes the intital DataTable is created and DataGrid is populated with an empty table when I click the Test button.
void FillDataGrid()
{
try
{
ds.ReadXml(#"C:\Temp\ToastData.ds");
gridToastItems.ItemsSource = ds.Tables[0].DefaultView;
}
catch (Exception ioException)
{
dt.Clear();
DataColumn column;
//ID Column
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
column.ReadOnly = true;
column.Unique = true;
column.AutoIncrement = true;
dt.Columns.Add(column);
//// Make the ID column the primary key column.
//DataColumn[] PrimaryKeyColumns = new DataColumn[1];
//PrimaryKeyColumns[0] = dt.Columns["id"];
//dt.PrimaryKey = PrimaryKeyColumns;
// Hostname column
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "hostname";
column.Caption = "Hostname";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
// Online column
column = new DataColumn();
column.DataType = System.Type.GetType("System.Boolean");
column.ColumnName = "online";
column.Caption = "Online";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
// OS Version column
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "osversion";
column.Caption = "OS Version";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
// Lockscreen status column
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "lockscreen";
column.Caption = "Lockscreen Status";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
// Toast type column
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "toasttype";
column.Caption = "Toast Type";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
// Schedule column
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "schedule";
column.Caption = "Schedule";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
// Result column
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "status";
column.Caption = "Status";
column.ReadOnly = false;
column.Unique = false;
column.AutoIncrement = false;
dt.Columns.Add(column);
ds.Tables.Add(dt);
gridToastItems.ItemsSource = dt.DefaultView;
//DataColumn hostname = new DataColumn("Hostname", typeof(string));
//DataColumn online = new DataColumn("Online", typeof(bool));
//DataColumn osversion = new DataColumn("OS Version", typeof(string));
//DataColumn lockscreen = new DataColumn("Lockscreen Status", typeof(string));
//DataColumn toastname = new DataColumn("Toast Type", typeof(string));
//DataColumn schedule = new DataColumn("Schedule", typeof(string));
//DataColumn result = new DataColumn("Result", typeof(string));
//dt.Columns.Add(hostname);
//dt.Columns.Add(online);
//dt.Columns.Add(osversion);
//dt.Columns.Add(lockscreen);
//dt.Columns.Add(toastname);
//dt.Columns.Add(schedule);
//dt.Columns.Add(result);
//dt.AcceptChanges();
//gridToastItems.ItemsSource = dt.DefaultView;
//ds.Tables.Add(dt);
//ds.AcceptChanges();
}
}
The computers are added to the DataTable from a second form:
private void AddToastEntries()
{
bool exceptionCaught = false;
try
{
int lineCount = txtComputerNames.LineCount; //iterator for number of computernames in the textbox
if (lineCount > 1)
{
for (int i = 0; i < lineCount; i++)
{
string currentLine = txtComputerNames.GetLineText(i).ReplaceLineEndings("");
//Adding a new toast entry for each computername listed in the textbox
if (currentLine != "")
{
DataRow firstRow = MainWindow.ds.Tables[0].NewRow();
firstRow["hostname"] = currentLine;
firstRow["online"] = false;
firstRow["osversion"] = "";
firstRow["lockscreen"] = "";
firstRow["toasttype"] = "Windows Update";
firstRow["schedule"] = SelectedDateTime();
firstRow["status"] = "Pending";
MainWindow.ds.Tables[0].Rows.Add(firstRow);
//MainWindow.ds.Tables[0].AcceptChanges();
//MainWindow.ds.AcceptChanges();
}
}
}
}catch(Exception newToastEntriesException)
{
exceptionCaught = true;
}
if(exceptionCaught)
{
MessageBox.Show("Failed to add current selection to schedule\n Check that a valid date and time is selected", "Error" ,MessageBoxButton.OK ,MessageBoxImage.Asterisk);
}
}
Here's the code running from the window above when I click the Start button
private async void timer_Tick(object sender, EventArgs e)
{
await Task.Run(() => ProcessToastMessages());
}
private void ProcessToastMessages()
{
WindowsToasts.WindowsToast windowsUpdateToast = new WindowsToast(); //creating a new instance of a toast message
int rowCount = 0;
rowCount = ds.Tables[0].Rows.Count;
for (int i = 0; i <= (rowCount - 1); i++)
{
DateTime scheduledTime = DateTime.Now;
//try
//{
DateTime.TryParse(ds.Tables[0].Rows[i]["schedule"].ToString(), out scheduledTime); //Converting the string value of date in the to a type of DateTime
string currentStatus = ds.Tables[0].Rows[i]["status"].ToString();
if ((scheduledTime.Ticks < DateTime.Now.Ticks) && currentStatus == "Pending")
{
string computerName = ds.Tables[0].Rows[i]["hostname"].ToString(); // Gets the computername in currentrow
bool isOnline = ComputerFuncs.ComputerOnline(computerName); // Checking if computer is online (Ping)
switch (isOnline)
{
case true:
//try
//{
ds.Tables[0].Rows[i].SetField("online", true);
//windowsUpdateToast.Send_WindwsUpdateToast(computerName); //Sending toast notification if computer is online
ds.Tables[0].Rows[i].SetField("status", "Sent");
//ds.Tables[0].Rows[i]["status"] = "Sent";
// break;
////}
////catch (Exception psException)
////{
// ds.Tables[0].Rows[i]["online"] = false;
//ds.Tables[0].Rows[i].SetField("online", false);
//ds.Tables[0].Rows[i].SetField("status", "Failed");
// ds.Tables[0].Rows[i]["status"] = "Failed";
// //break;
//}
break;
case false:
ds.Tables[0].Rows[i].SetField("online", false);
break;
}
}
//}
//catch (Exception dateTimeException)
//{
//}
}
}
private void btn_StartStop_Click(object sender, RoutedEventArgs e)
{
// ds.WriteXml((#"C:\temp\ToastData.ds"), XmlWriteMode.WriteSchema);
string btnCurrentText = btn_StartStop.Content.ToString();
if(btnCurrentText == "Start")
{
gridToastItems.IsReadOnly = true;
btn_Schedule.IsEnabled = false;
StartToastMonitoring(true);
}
else if(btnCurrentText == "Stop")
{
StartToastMonitoring(false);
gridToastItems.IsReadOnly = false;
btn_Schedule.IsEnabled = true;
}
}
Error I'm getting is shown below. The iterator seems to be within bounds of the number of rows as far as I can tell.
I have figured what is causing problems. The process of pinging the computers is taking an extreme amount of time if the ping function is unable to get a ping result and a ping exception is thrown.
The interval of the timer had to be increased to allow all the processing to complete. I will figure out another way and try to ping the computers in parallel.
I have a problem about getting values from gridview that i created in code behind.
I created dynamic gridview. I filled DataSource from Database. These are my codes:
SqlCommand cmd = new SqlCommand("xxx", noz);
cmd.CommandType = CommandType.StoredProcedure;
noz.Open();
i = 1;
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
string isim = "name" + i;
Label name4 = new Label();
name4.ID = isim;
name4.Text = rd3[1].ToString() + " için değerlendirme yapınız";
name4.Font.Bold = true;
ph.Controls.Add(name4);
noz2.Open();
SqlDataAdapter sda = new SqlDataAdapter("xxx", noz2);
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
GridView gv = new GridView();
gv.ID = "_gridview" + i;
Queue q = new Queue();
q.Enqueue(i);
DataTable dt = new DataTable();
sda.Fill(dt);
dt.Columns.Add("Puanlar", typeof(string));
gv.DataSource = dt;
gv.DataBind();
ph.Controls.Add(gv); //ph is my placeholder//
gv.Height = 500;
gv.Width = 980;
i++;
noz2.Close();
foreach (GridViewRow r in gv.Rows)
{
TextBox ddl3Selection = new TextBox();
ddl3Selection.Width = 800;
r.Cells[2].Controls.Add(ddl3Selection);
}
}
noz.Close();
I have no problem so far. But when i want to use click button, i can't get gridviews's rows. I get rowcount 0.
for (int a = 1; a < i; a++)
{
GridView gv = new GridView();
gv.ID = "_gridview" + a;
Label lbl = new Label();
lbl.ID = "name" + a;
for (int n = 0; n < gv.Rows.Count; n++)
{
SqlCommand cmd = new SqlCommand("xxx", noz);
cmd.CommandType = CommandType.StoredProcedure;
GridViewRow row = gv.Rows[n];
int soruid =Convert.ToInt16(row.Cells[0].Text);
string cevap = row.Cells[2].Text;
string firmaadi = lbl.Text;
cmd.Parameters.AddWithValue("#Firma_Ad", firmaadi);
cmd.Parameters.AddWithValue("#Soru_Id", soruid);
cmd.Parameters.AddWithValue("#Soru_Cevap", cevap);
cmd.Parameters.AddWithValue("#Cevaplayan", "");
noz.Open();
int rd2 = cmd.ExecuteNonQuery();
noz.Close();
}
How can i get values from gridview?
there is two different grid. First grid have data source and the second is nothing.
I'm trying to add variables from a text file into a datatable to be converted into a CSV file but I keep getting this error: "A column named 'Machine Number' already belongs to this DataTable" Im not sure what to do, any help would be appreciated, Thanks :)
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Globalization;
using System.Text;
namespace Ispy
{
public partial class Form1 : Form
{
private DataGridView dexRead;
DataColumn column;
DataTable Data = new DataTable("ISpy");
DataSet dataSet = new DataSet();
DataRow row;
public Form1()
{
InitializeComponent();
ReadFiles();
}
private void ReadFiles()
{
DataTable dataTable;
//Location of Dex Files
DirectoryInfo DexFiles = new DirectoryInfo(Properties.Settings.Default.Dex_File_Path);
//List of file names in Dex File folder
List<string> DexNames = new List<string>();
//Location of Input File
string ExcelFile = Properties.Settings.Default.Excel_File_Path;
//Read Input File
string[] ExcelLines = File.ReadAllLines(ExcelFile);
//Add names of each file to a list
foreach (FileInfo DexFile in DexFiles.GetFiles("*.dex"))
{
DexNames.Add(DexFile.Name);
}
//Excel Input and Dex File Data Marriage
foreach (string Line in ExcelLines)
{
row = Data.NewRow();
dataTable = new DataTable();
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "Machine Number";
column.ReadOnly = false;
column.Unique = true;
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Customer";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "MEI Total Vend Count";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "DEX Total Vend Count";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "Stock Sold";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "Capacity";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.DateTime");
column.ColumnName = "Next Scheduled Visit Date";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Scheduled Visit In:";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Scheduled Visit Day";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Next Visit Stock Prediction";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Route Number";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Route Driver Name";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Current Stock %";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.DateTime");
column.ColumnName = "Date/Time of DEX";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Telemetry Provider";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Days since last refill";
column.AutoIncrement = false;
Data.Columns.Add(column);
//column = new DataColumn();
//column.DataType = System.Type.GetType("System.String");
//column.ColumnName = "Machine #40% Stock in";
//column.AutoIncrement = false;
//Data.Columns.Add(column);
//column = new DataColumn();
//column.DataType = System.Type.GetType("System.String");
//column.ColumnName = "Machine #30% Stock in";
//column.AutoIncrement = false;
//Data.Columns.Add(column);
//column = new DataColumn();
//column.DataType = System.Type.GetType("System.String");
//column.ColumnName = "Optimal Fill Date";
//column.AutoIncrement = false;
//Data.Columns.Add(column);
//column = new DataColumn();
//column.DataType = System.Type.GetType("System.String");
//column.ColumnName = "Optimal Fill Date In:";
//column.AutoIncrement = false;
//Data.Columns.Add(column);
//column = new DataColumn();
//column.DataType = System.Type.GetType("System.String");
//column.ColumnName = "Optimal Fill Day";
//column.AutoIncrement = false;
//Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Sector";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Products";
column.AutoIncrement = false;
Data.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Machine Type";
column.AutoIncrement = false;
Data.Columns.Add(column);
string[] LineInfo = Line.Split(',');
//Input File Variables (.Trim('"') is to remove artifacts leftover from Input File)
string MachineNumber = LineInfo[0].Trim('"');
string MachineLocation = LineInfo[1].Trim('"');
string TelemetryProvider = LineInfo[7].Trim('"');
string Capacity = LineInfo[9].Trim('"');
string MEIVendCount = LineInfo[10].Trim('"');
string MEICashCount = LineInfo[11].Trim('"');
string LastVisitDate = LineInfo[12].Trim('"');
string MachinePHYSID = LineInfo[13].Trim('"');
string NextScheduledVisit = LineInfo[14].Trim('"');
string RouteName = LineInfo[16].Trim('"');
string DriverName = LineInfo[17].Trim('"');
string MachineModel = LineInfo[18].Trim('"');
string MachineType = LineInfo[19].Trim('"');
string MachineSector = LineInfo[20].Trim('"');
string DEXVendCount = "";
string DEXCashCount = "";
string Difference = "";
string NextScheduledVisitDays = "";
string NextScheduledVisitDay = "";
string NextVisitStockPrediction = "";
string MachineStockSold = "";
string DexNameDate = "";
string DaysSinceLastFill = "";
string MachineStockAt30In = "";
string OptimalFillDate = "";
string OptimalFillDay = "";
//Read each Dex File and retrieve data
foreach (string DexName in DexNames)
{
string[] DexNameData = DexName.Split('_', '.');
int DexPHYSID = Int32.Parse(DexNameData[0]);
string dexNameDate = DexNameData[1] + DexNameData[2];
try
{
//Marriage of Excel File Data and Dex File Data
if (Int32.Parse(MachinePHYSID) == DexPHYSID)
{
//Dex File Variable's
string MeterLine = "";
//Calculate location of each Dex File
string DexFilePath = DexFiles.ToString() + DexName;
//Read all of the Dex File's lines and add to an array
string[] DexLines = File.ReadAllLines(DexFilePath);
//Find Meter Read line and add to an array
foreach (string DexLine in DexLines)
{
MeterLine = Array.Find(DexLines,
element => element.StartsWith("VA1", StringComparison.Ordinal));
}
//Split data from Meter Read line
if (MeterLine != null)
{
string[] MeterReads = MeterLine.Split('*');
//Assign Dex values to Dex variables
DEXCashCount = MeterReads[1];
DEXVendCount = MeterReads[2];
}
DateTime creationDate = DateTime.ParseExact(dexNameDate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
DateTime nextScheduledVisit = DateTime.ParseExact(NextScheduledVisit, "ddMMyy", CultureInfo.InvariantCulture);
TimeSpan scheduleDays = DateTime.Today - nextScheduledVisit;
TimeSpan LastVisitDays = DateTime.Today - DateTime.ParseExact(LastVisitDate, "ddMMyy", CultureInfo.InvariantCulture);
int Differential = Int32.Parse(DEXVendCount) - Int32.Parse(MEIVendCount);
int stockSold = Int32.Parse(Capacity) - Differential;
double percent = 0;
if (stockSold != 0)
{
percent = (double)(stockSold * 100) / Int32.Parse(Capacity);
}
else
{
percent = 0;
}
row["Machine Number"] = Int32.Parse(MachineNumber);
row["Customer"] = MachineLocation;
row["MEI Total Vend Count"] = Int32.Parse(MEIVendCount);
row["DEX Total Vend Count"] = Int32.Parse(DEXVendCount);
row["Stock Sold"] = Differential;
row["Capacity"] = Int32.Parse(Capacity);
row["Next Scheduled Visit Date"] = DateTime.ParseExact(NextScheduledVisit, "ddMMyy", CultureInfo.InvariantCulture);
row["Scheduled Visit In:"] = scheduleDays.Days.ToString() + " Days";
row["Scheduled Visit Day"] = nextScheduledVisit.DayOfWeek.ToString();
row["Next Visit Stock Prediction"] = "N/A";
row["Route Number"] = RouteName;
row["Route Driver Name"] = DriverName;
row["Current Stock %"] = percent.ToString() + " %";
row["Date/Time of DEX"] = creationDate;
row["Telemetry Provider"] = TelemetryProvider;
row["Days since last refill"] = LastVisitDays.Days.ToString() + " Days";
row["Sector"] = MachineSector;
row["Products"] = MachineModel;
row["Machine Type"] = MachineType;
dataTable.ImportRow(row);
}
}
catch(Exception e)
{
}
}
}
dataSet.Tables.Add(Data);
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = Data.Columns.Cast<DataColumn>().
Select(column1 => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row1 in Data.Rows)
{
IEnumerable<string> fields = row1.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText(#"\\DC01\Dev\Dexr\Excel Files\Output\test.csv", sb.ToString());
}
private void Load_Properties()
{
string configFile = "config.cfg";
string path = Path.Combine(Environment.CurrentDirectory, #"Data\", configFile);
}
}
}
You need to declare datatable and add data columns only once outside foreach loop.
//Prepare Datatable and Add All Columns Here
dataTable = new DataTable();
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "Machine Number";
column.ReadOnly = false;
column.Unique = true;
column.AutoIncrement = false;
//Excel Input and Dex File Data Marriage
foreach (string Line in ExcelLines)
{
//Add new row and assign values to columns, no need to add columns again and again in loop which will throw exception
row = dataTable.NewRow();
//Map all the values in the columns
row["ColumnName"]= value;
//At the end just add that row in datatable
dataTable.Rows.Add(row );
}
i see you add columns to DataTable Data every time in foreach loop
so try adding these column outside the loop
private void sBAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("MonthlyActualPeriod1", typeof(System.Int32));
dt.Columns.Add("MonthlyActualPeriod2", typeof(System.Int32));
dt.Columns.Add("YearlyActualYear1", typeof(System.Int32));
dt.Columns.Add("YearlyActualYear2", typeof(System.Int32));
dt.Columns.Add("MonthlyBudgetPeriod1", typeof(System.Int32));
dt.Columns.Add("MonthlyBudgetPeriod2", typeof(System.Int32));
dt.Columns.Add("YearlyBudgetYear1", typeof(System.Int32));
dt.Columns.Add("YearlyBudgetYear2", typeof(System.Int32));
dt.Columns.Add("MonthlyActualCurrentPeriod", typeof(System.Int32));
dt.Columns.Add("YearlyActualCurrentyear", typeof(System.Int32));
dt.Columns.Add("YearlyActualPrioryear", typeof(System.Int32));
dt.Columns.Add("MonthlyBudgetCurrentPeriod", typeof(System.Int32));
dt.Columns.Add("YearlyBudgetCurrentyear", typeof(System.Int32));
dt.Columns.Add("YearlyBudgetPrioryear", typeof(System.Int32));
for (int i = 1; i < 61; i++)
{
dt.Columns.Add("MonthlyActualCurrentPeriod-" + i, typeof(System.Int32));
dt.Columns.Add("MonthlyBudgetCurrentPeriod-" + i, typeof(System.Int32));
}
int j = dt.Columns.Count;
DataRow row;
foreach (DataColumn cl in dt.Columns)
{
row = dt.NewRow();
for (int i = 0; i < j; i++)
{
row[i] = 1;
}
dt.Rows.Add(row);
}
this.gcCalcFields.DataSource = dt;
// Create an unbound column.
GridColumn unbColumn = gridView1.Columns.AddField("CalcFields");
unbColumn.VisibleIndex = gridView1.Columns.Count;
unbColumn.UnboundType = DevExpress.Data.UnboundColumnType.Object;
ColumnFilterMode prev = unbColumn.FilterMode;
unbColumn.FilterMode = ColumnFilterMode.Value;
gridView1.ShowUnboundExpressionEditor(unbColumn);
unbColumn.FilterMode = prev;
string Calculation = "";
Calculation = unbColumn.UnboundExpression;
LBCCalcFieldsActual.Items.Add(Calculation);
gridView1.Columns.Remove(gridView1.Columns["CalcFields"]);
}
I want to display a simple color on the background of the cells int the color column only?
how do I display the color instead of the color code atleast the background color of the cell itself? btw i'm using the fullrowselect..
my code for loading the database
SuspendLayout();
using (MySqlConnection conn = new MySqlConnection(myConnection))
{
//string cell = dataGridView3.CurrentCell.Value.ToString();
conn.Open();
string query = "SELECT productid,description,color,quantity,unitprice FROM deqor.tblproducts where category=?cat;";
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("?cat", comboBox1.SelectedItem.ToString());
try
{
sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
datset = new DataTable();
sda.Fill(datset);
bsource = new BindingSource();
bsource.DataSource = datset;
dataGridView1.DataSource = bsource;
DataGridViewColumn column = dataGridView1.Columns[0];
column.HeaderText = "Code";
column.Width = 160;
DataGridViewColumn column1 = dataGridView1.Columns[1];
column1.HeaderText = "Brand";
column1.Width = 220;
DataGridViewColumn column2 = dataGridView1.Columns[2];
column2.HeaderText = "Color";
column2.Width = 100;
DataGridViewColumn column3 = dataGridView1.Columns[3];
column3.HeaderText = "Quantity";
column3.Width = 50;
DataGridViewColumn column4 = dataGridView1.Columns[4];
column4.HeaderText = "Price";
column4.Width = 50;
sda.Update(datset);
if (dataGridView1.RowCount < 1)
{
datset.Clear();
string row = "NO items found";
datset.Rows.Add(row);
}
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
conn.Close();
}
ResumeLayout();
You could set the color during the CellFormatting event, see here for an explanation
Example
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//Check if we're formatting the color column
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Color")
{
//Make sure there's a value set
if (e.Value != null)
{
string colorCode = (string)e.Value;
ColorConverter cc = new ColorConverter();
e.CellStyle.BackColor = (Color)cc.ConvertFromString("#" + colorCode);
//If you don't want the code to show
e.Value = "";
e.FormattingApplied = true;
}
}
}
you can use foreach for every cell in column[2] and fill it like that:
dataGridView1.Rows[count].DefaultCellStyle.BackColor = (Color)ColorConverter.ConvertFromString("#FFDFD991");
I have created a datagridview programmatically.
So there is no bindingsource or datasource that we can connect both of the Datagridview and Binidgnavigator to them.
Is there any other way to connect them to each other.
Here is my code for datafridview
Help me to connect it to a bindingNavigator
private void Fill()
{
try
{
if (dataGridView1 != null)
{
dataGridView1.ColumnCount = 11;
dataGridView1.Columns[0].HeaderText = Resources.Form1_Fill_ID;
dataGridView1.Columns[1].HeaderText = Resources.Form1_Fill_Family;
dataGridView1.Columns[2].HeaderText = Resources.Form1_Fill_Cellphone;
dataGridView1.Columns[3].HeaderText = Resources.Form1_Fill_Phone1;
dataGridView1.Columns[4].HeaderText = Resources.Form1_Fill_Phone2;
dataGridView1.Columns[5].HeaderText = Resources.Form1_Fill_Phone3;
dataGridView1.Columns[6].HeaderText = Resources.Form1_Fill_Fax;
dataGridView1.Columns[7].HeaderText = Resources.Form1_Fill_CompanyName;
dataGridView1.Columns[8].HeaderText = Resources.Form1_Fill_Agency;
dataGridView1.Columns[9].HeaderText = Resources.Form1_Fill_Brands;
dataGridView1.Columns[10].HeaderText = Resources.Form1_Fill_Address;
dataGridView1.Columns[0].Name = Resources.Form1_Fill_ID;
dataGridView1.Columns[1].Name = Resources.Form1_Fill_Family;
dataGridView1.Columns[2].Name = Resources.Form1_Fill_Cellphone;
dataGridView1.Columns[3].Name = Resources.Form1_Fill_Phone1;
dataGridView1.Columns[4].Name = Resources.Form1_Fill_Phone2;
dataGridView1.Columns[5].Name = Resources.Form1_Fill_Phone3;
dataGridView1.Columns[6].Name = Resources.Form1_Fill_Fax;
dataGridView1.Columns[7].Name = Resources.Form1_Fill_CompanyName;
dataGridView1.Columns[8].Name = Resources.Form1_Fill_Agency;
dataGridView1.Columns[9].Name = Resources.Form1_Fill_Brands;
dataGridView1.Columns[10].Name = Resources.Form1_Fill_Address;
}
_conn.ConnectionString = _connectionString;
var cmd = new OleDbCommand("Select * from contacts ", _conn);
_conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
int i = 0;
while (reader != null && reader.Read())
{
if (dataGridView1 != null)
{
dataGridView1.Rows.Add(1);
}
if (dataGridView1 != null)
{
var row = dataGridView1.Rows[i];
row.Cells[Resources.Form1_Fill_ID].Value = reader[0].ToString();
row.Cells[Resources.Form1_Fill_Family].Value = reader[1].ToString();
row.Cells[Resources.Form1_Fill_Cellphone].Value = reader[2].ToString();
row.Cells[Resources.Form1_Fill_Phone1].Value = reader[3].ToString();
row.Cells[Resources.Form1_Fill_Phone2].Value = reader[4].ToString();
row.Cells[Resources.Form1_Fill_Phone3].Value = reader[5].ToString();
row.Cells[Resources.Form1_Fill_Fax].Value = reader[6].ToString();
row.Cells[Resources.Form1_Fill_CompanyName].Value = reader[7].ToString();
row.Cells[Resources.Form1_Fill_Agency].Value = reader[8].ToString();
row.Cells[Resources.Form1_Fill_Brands].Value = reader[9].ToString();
row.Cells[Resources.Form1_Fill_Address].Value = reader[10].ToString();
}
i++;
}
}
catch (Exception ex)
{
return;
}
finally
{
_conn.Close();
}
}
Try to revise your code. You don't need to create a column programmactically, your query itself could create a column through DataTable to BindingSource, try this code and get some idea.
BindingNavigator and BindingSource
string connectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=D:\myDatabase.accdb;";
string queryString = "SELECT Name AS FullName, Gender AS Gender, Address AS [Current Address] FROM Person";
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(queryString, connection))
{
try
{
BindingSource bs = new BindingSource();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(queryString, connection);
OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(dataAdapter);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
bs.DataSource = dataTable;
dataGridView1.DataSource = bs;
bindingNavigator1.BindingSource = bs;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}