DataTable automatically re-initializes itself - c#

Why does my DataTable automatically reset to null value inside of my event?
After the for loop ends the DataTable resets to null and doesn't keep the value in the public field. Even though I have another event that does the same thing but it can hold the DataTable.
Public DataTable d = new DataTable();
private void btnCSVgetter_Click(object sender, EventArgs e)
{
emptyDataGrid();
var csv = new OpenFileDialog();
csv.Title = "Select CSV to Upload";
csv.DefaultExt = "*.csv";
csv.Filter = "CSV files| *.csv";
if (csv.ShowDialog() == DialogResult.OK)
{
string safeName = csv.SafeFileName;
string filename = csv.FileName;
string filedirectory = csv.FileName.Substring(0, filename.IndexOf(safeName));
if (IsFileLocked(filename)) { MessageBox.Show("File is in use by another user, close and try again"); return; }
var con = new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Text;HDR=YES;FMT=Delimited\"", filedirectory));
var cmd = new OleDbCommand(String.Format("select * from [" + safeName + "]"), con);
con.Open();
var csvDA = new OleDbDataAdapter(cmd);
var d = new DataTable();
csvDA.Fill(d);
DGVUpload.DataSource = d;
con.Close();
d.Columns.Remove("Symbol");
foreach (DataColumn col in d.Columns)
{
if (col.ColumnName == "Ric Code")
col.ColumnName = "Symbol";
else if (col.ColumnName == "AveragePrice")
col.ColumnName = "Avg_Price";
else if (col.ColumnName == "Accounts")
col.ColumnName = "ClientAcct";
else if (col.ColumnName == "Executed")
col.ColumnName = "Quantity";
} // After this line datatable d resets to null
// MoreCode...
}

Your code snippet has two declarations of DataTable d:
Public DataTable d = new DataTable(); <---- here
private void btnCSVgetter_Click(object sender, EventArgs e)
{
emptyDataGrid();
OpenFileDialog csv = new OpenFileDialog();
csv.Title = "Select CSV to Upload";
csv.DefaultExt = "*.csv";
csv.Filter = "CSV files| *.csv";
if (csv.ShowDialog() == DialogResult.OK)
{
string safeName = csv.SafeFileName;
string filename = csv.FileName;
string filedirectory = csv.FileName.Substring(0, filename.IndexOf(safeName));
if (IsFileLocked(filename) == true) { MessageBox.Show("File is in use by another user, close and try again"); return; }
OleDbConnection con = new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Text;HDR=YES;FMT=Delimited\"", filedirectory));
OleDbCommand cmd = new OleDbCommand(String.Format("select * from [" + safeName + "]"), con);
con.Open();
OleDbDataAdapter csvDA = new OleDbDataAdapter(cmd);
DataTable d = new DataTable(); <----- here
csvDA.Fill(d);
When you do this, the inner if statement is operating on the local d variable, not the class variable declared outside the method. Once the local d goes out of scope, the only d available to you is the one at the class level, which is empty.

Related

How to see a number with more than 15 characters in a DataGridView?

I'm trying to import from a CSV file into DataGridView a number that is longer than 15 characters. In the CSV file it looks like 8940012004412026012but after import in the DataGridView is presented as 8.9400120044120259E + 18.
This is my present code:
public static DataTable GetDataTable(string strFileName)
{
ADODB.Connection oConn = new ADODB.Connection();
oConn.Open("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";", "", "", 0);
string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
ADODB.Recordset rs = new ADODB.Recordset();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
DataTable dt = new DataTable();
rs.Open(strQuery, "Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";",
ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1);
adapter.Fill(dt, rs);
return dt;
}
private void Import()
{
if (textBox4.Text.Trim() != string.Empty)
{
try
{
DataTable ct = GetDataTable(textBox4.Text);
dataGridView2.AllowUserToAddRows = false;
dataGridView2.DataSource = ct;
dataGridView2.Columns[0].HeaderCell.Value = "1";
dataGridView2.Columns[1].HeaderCell.Value = "2";
dataGridView2.Columns[2].HeaderCell.Value = "3";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
dataGridView2.Columns[2].HeaderCell.Value = "3";
needs to be 8940012004412026012
Thanks for the suggestion to use CsvHelper this is the solution i found
private void button60_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Select file";
fdlg.InitialDirectory = #"c:\";
fdlg.FileName = textBox4.Text;
fdlg.Filter = "Text and CSV Files(*.txt, *.csv)|*.txt;*.csv|Text Files(*.txt)|*.txt|CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
fdlg.FilterIndex = 1;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
using (var reader = new StreamReader(fdlg.FileName))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
using (var dr = new CsvDataReader(csv))
{
var dt = new DataTable();
dt.Load(dr);
dataGridView2.DataSource = dt;
}
}
}
}

How to convert Linq select new to DataTable

How to convert select new LINQ to DataTable
I need to compare several files using Windows Application form C#.
I have use LINQ and Lambda expression to sum up the duplicates
Please help thanks
I had seen Convert select new to DataTable?. and tried
var firstRecord = records.First();
if (firstRecord == null)
return;
var infos = firstRecord.GetType().GetProperties();
DataTable table = new DataTable();
foreach (var info in infos) {
DataColumn column = new DataColumn(info.Name, info.PropertyType);
table.Columns.Add(column);
}
foreach (var record in records) {
DataRow row = table.NewRow();
for (int i = 0; i < table.Columns.Count; i++)
row[i] = infos[i].GetValue(record);
table.Rows.Add(row);
}
But it had errors for sequence contains no elements.
These are my full codes.
namespace Comparison2._0
{
public partial class ComparisonForm : Form
{
public class FlatFile
{
public string Location { get; set; }
public string Item_Type { get; set; }
public string Type { get; set; }
public double Amount { get; set; }
}
public ComparisonForm()
{
InitializeComponent();
}
private void UploadTransactionReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
String path = dialog.FileName;
//String fileName = path.Substring(path.LastIndexOf("\\") + 1);
TransactionFileNameTextBox.Text = path;
}
}
private void UploadMovementReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
String path = dialog.FileName;
//String fileName = path.Substring(path.LastIndexOf("\\") + 1);
MovementReportTextBox.Text = path;
}
}
private void UploadFlatfileReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
String[] path = dialog.FileNames;
//String fileName = path.Substring(path.LastIndexOf("\\") + 1);
for (int i = 0; i < path.Count(); i++)
FlatfileTextBox.Text += path[i] + "#";
}
}
private void UploadAdjustmentReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
String path = dialog.FileName;
AdjustmentReportTextBox.Text = path;
}
}
private void CompareButton_Click(object sender, EventArgs e)
{
OleDbConnection objConn, objConn1, objConn2;
DataTable dt, dt1, dt2, TableA, TableB, TableC;
string sql, sql1, sql2;
OleDbDataAdapter oleDA;
DataSet ds;
string transactionReport = TransactionFileNameTextBox.Text;
string movementReport = MovementReportTextBox.Text;
string adjustmentReport = AdjustmentReportTextBox.Text;
String sConnectionString1 = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
transactionReport + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
String sConnectionString2 = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source="
+ movementReport + ";" + "Extended Properties =\"Excel 12.0;HDR=YES;IMEX=1\"";
String sConnectionString3 = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source="
+ adjustmentReport + ";" + "Extended Properties =\"Excel 12.0;HDR=YES;IMEX=1\"";
//TRANSACTION FILE
objConn = new OleDbConnection(sConnectionString1);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sql = "SELECT * from [Sheet$]";
oleDA = new OleDbDataAdapter(sql, sConnectionString1);
ds = new DataSet();
oleDA.Fill(ds);
TableA = ds.Tables[0];
objConn.Close();
//dataGridView.DataSource = _DtTable;
//MOVEMENT FILE
objConn1 = new OleDbConnection(sConnectionString2);
objConn1.Open();
dt1 = objConn1.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sql1 = "SELECT * from [Sheet$]";
oleDA = new OleDbDataAdapter(sql1, sConnectionString2);
ds = new DataSet();
oleDA.Fill(ds);
TableB = ds.Tables[0];
objConn1.Close();
//dataGridView.DataSource = _DtTable1;
//ADJUSTMENT FILE
objConn2 = new OleDbConnection(sConnectionString3);
objConn2.Open();
dt2 = objConn2.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sql2 = "SELECT * from [Sheet$]";
oleDA = new OleDbDataAdapter(sql2, sConnectionString3);
ds = new DataSet();
oleDA.Fill(ds);
TableC = ds.Tables[0];
objConn2.Close();
//dataGridView1.DataSource = TableC;
//FLATFILES
//List<string> fileLines = System.IO.File.ReadAllLines(FlatfileTextBox.Text).ToList();
DataTable TableD = ConvertToDataTable(FlatfileTextBox.Text, 4);
//dataGridView1.DataSource = tableD;
DataTable FlatFileTable = new DataTable();
FlatFileTable.Columns.Add(new DataColumn("Location"));
FlatFileTable.Columns.Add(new DataColumn("Item Type"));
FlatFileTable.Columns.Add(new DataColumn("Type"));
FlatFileTable.Columns.Add(new DataColumn("PO Total Cost(Qty Received)"));
FlatFileTable.Columns.Add(new DataColumn("Amount", typeof(double)));
FlatFileTable.Columns.Add(new DataColumn("Amount Difference"));
foreach (DataRow rowA in TableA.Rows)
{
foreach (DataRow rowD in TableD.Rows)
{
if (Convert.ToDouble(rowD["Amount"]) > 0)
{
if (rowA["Location"].ToString().Substring(0, 5).Trim() == rowD["Location"].ToString() && rowD["Type"].ToString() == "GRN" && rowA["Item Type"].ToString() == rowD["Item Type"].ToString())
{
var newRow = FlatFileTable.NewRow();
newRow["Location"] = rowD["Location"];
newRow["Item Type"] = rowD["Item Type"];
newRow["Type"] = rowD["Type"];
newRow["PO Total Cost(Qty Received)"] = rowA["PO Total Cost(Qty Received)"];
//sum += Convert.ToDouble(rowD["Amount"]);
newRow["Amount"] = rowD["Amount"];
var newSort = from row in FlatFileTable.AsEnumerable()
group row by new { Location = row.Field<string>("Location"), Item_Type = row.Field<string>("Item Type"), Type = row.Field<string>("Type") } into grp
select new
{
Location = grp.Key.Location,
//Item_Type = grp.Key.Item_Type,
Type = grp.Key.Type,
Amount = grp.Sum(r => r.Field<double>("Amount"))
};
//dataGridView1.DataSource = table;
//newRow["Amount Difference"] = Convert.ToDouble(rowA["PO Total Cost(Qty Received)"]) - Convert.ToDouble(rowD["Amount"]);
FlatFileTable.Rows.Add(newRow);
//FlatFileTable.Rows.Add(newSort.ToList());
//dataGridView1.DataSource = FlatFileTable;
//DataTable TableZ = newSort.Copt
dataGridView.DataSource = Comparison(TableA, TableB, FlatFileTable);
}
}
}
}
//dataGridView1.DataSource = FlatFileTable;
//dataGridView.DataSource = Comparison(TableA, TableB, newSort.);
//I want to pass into this function so I can compare between them
}
public DataTable ConvertToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("Type"));
tbl.Columns.Add(new DataColumn("Amount", typeof(double)));
tbl.Columns.Add(new DataColumn("Location"));
tbl.Columns.Add(new DataColumn("Item Type"));
//foreach(var file in filePath)
string[] MultipleFiles = filePath.Split('#');
for (int i = 0; i < MultipleFiles.Count() - 1; i++)
{
string[] lines = System.IO.File.ReadAllLines(MultipleFiles[i]);
foreach (string line in lines)
{
var cols = line.Split('|');
var count = 0;
DataRow dr = tbl.NewRow();
for (int cIndex = 7; cIndex < 11; cIndex++)
{
dr[count] = cols[cIndex];
count++;
}
tbl.Rows.Add(dr);
}
}
return tbl;
}
public DataTable Comparison(DataTable A, DataTable B, DataTable C)
{
var tableC = new DataTable();
tableC.Columns.Add(new DataColumn("Location"));
tableC.Columns.Add(new DataColumn("Item Type"));
tableC.Columns.Add(new DataColumn("PO Total Cost(Qty Received)"));
tableC.Columns.Add(new DataColumn("Qty Received Actual Cost"));
tableC.Columns.Add(new DataColumn("Amount from FlatFile"));
tableC.Columns.Add(new DataColumn("Amount (Transaction - Movement)"));
tableC.Columns.Add(new DataColumn("Amount (Transaction - FlatFile)"));
foreach (DataRow rowA in A.Rows)
{
foreach (DataRow rowB in B.Rows)
{
foreach (DataRow rowC in C.Rows)
{
if (rowA["Location"].ToString() == rowB["Location"].ToString() && rowA["Item Type"].ToString() == rowB["Item Type"].ToString() &&
rowA["Location"].ToString().Substring(0, 5).Trim() == rowC["Location"].ToString() && rowA["Item Type"].ToString() == rowC["Item Type"].ToString())
{
var newRow = tableC.NewRow();
newRow["Location"] = rowA["Location"];
newRow["Item Type"] = rowA["Item Type"];
newRow["PO Total Cost(Qty Received)"] = rowA["PO Total Cost(Qty Received)"];
newRow["Qty Received Actual Cost"] = rowB["Qty Received Actual Cost"];
newRow["Amount from FlatFile"] = rowC["Amount"];
newRow["Amount (Transaction - Movement)"] = Convert.ToDouble(rowA["PO Total Cost(Qty Received)"]) - Convert.ToDouble(rowB["Qty Received Actual Cost"]);
newRow["Amount (Transaction - FlatFile)"] = Convert.ToDouble(rowA["PO Total Cost(Qty Received)"]) - Convert.ToDouble(rowC["Amount"]);
tableC.Rows.Add(newRow);
}
//}
}
}
}
return tableC;
}
private void ComparisonForm_Load(object sender, EventArgs e)
{
}
}
}
But it had errors for sequence contains no elements.
You are getting the above error because there is no record in the collection apparently and First fails in that case. You need FirstOrDefault which will return null if there is no items in the collection:
var firstRecord = records.FirstOrDefault();

Combobox in a datagridview

I want to put a combobox in my datagridview. I've tried differents ways (creating a var list<>, creating an arraylist, ect...) and none is working. The thing is my column already exist because of my select query that show my database in the datagridview. But the column is empty since in my database the column is fill with NULL value.
I have two choices : Creating a combobox and do an addcolumn, or if you know how to do it link my combobox to the already existing column. And obviously i need help creating my combobox.
Thank you !
My code :
public partial class Repair : Form
{
public Repair()
{
Main pp = new Main();
InitializeComponent();
this.label4.Text = pp.label3.Text;
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE FComponent IS NOT NULL";
}
else
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "FaultCodeByOp";
combo.Name = "combo";
ArrayList list = new ArrayList();
list.Add("C-C");
list.Add("C-O");
combo.Items.AddRange(list.ToArray());
dataGridView1.Columns.Add(combo);
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for(int i=0;i<4;i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
foreach (DataGridViewRow row in dataGridView2.Rows)
{
for(int i=0;i<3;i++)
{
dataGridView2.Columns[i].ReadOnly = true;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Main ff = new Main();
ff.Show();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
string Var1 = textBox1.Text;
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailAndPass WHERE BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE SerialNum LIKE #SerialNum AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE SerialNum LIKE #SerialNum And FComponent IS NOT NULL";
}
}
else
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailOnly WHERE (BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent) AND ReportingOperator IS NULL ";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL ";
command1.CommandText = "SELECT DISTINCT Machine, BoardName, BoardNumber FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
}
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells[6].Value != null) && (bool)row.Cells[6].Value)
{
SqlCommand command = maConnexion.CreateCommand();
command = new SqlCommand("update FailAndPass set FaultCodeByOp=#Fault, RepairingDate=#RD, RepairingTime = #RT, ReportingOperator=#RO WHERE SerialNum=#Serial", maConnexion);
command.Parameters.AddWithValue("#Fault", row.Cells[4].Value != null ? row.Cells[4].Value : DBNull.Value);
command.Parameters.AddWithValue("#RD", DateTime.Today.ToString("d"));
command.Parameters.AddWithValue("#RT", row.Cells[5].Value != null ? row.Cells[5].Value : DBNull.Value);
command.Parameters.AddWithValue("#RO", this.label4.Text);
command.Parameters.AddWithValue("#Serial", this.textBox1.Text);
command.ExecuteNonQuery();
}
}
maConnexion.Close();
this.Hide();
Repair rep = new Repair();
rep.Show();
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.IsCurrentRowDirty)
{
dataGridView1.Rows[e.RowIndex].Cells[6].Value = true;
}
}
}
private void ComboboxInDatagridview()
{
var dataGridView1 = new DataGridView();
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "FaultCodeByOp";
combo.Name = "combo";
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { combo });
ArrayList list = new ArrayList() { "C-C", "C-O" };
var rowindex = dataGridView1.Rows.Add();
DataGridViewComboBoxCell cmbCell = (DataGridViewComboBoxCell)dataGridView1["combo", rowindex];
//Or
//var columnindex = 0;
//DataGridViewComboBoxCell cmbCell = (DataGridViewComboBoxCell)dataGridView1[columnindex, rowindex];
cmbCell.DataSource = list;
}
Anyone having other solutions ? I've tried something else :
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
ArrayList list1 = new ArrayList(); //{ "C-C", "C-O", "Absence composant", "Mauvaise valeur", "Mauvais sens", "Mauvais composant" };
list1.Add("C-C");
list1.Add("C-O");
combo.DataSource = list1;
combo.HeaderText = "FaultCodeByOp";
combo.DataPropertyName = "FaultCodeByOp";
dataGridView1.Columns.AddRange(combo);
didnt change anything.
I dont know what i've done, but it is not greyish anymore. Now it is white like other columns.... but it doesnt dropdown, nor show members of the list.

how to load images from excel to datagridview

I want to load images in the datagridview, but so far I am getting only text.
CODE
private void button1_Click(object sender, EventArgs e)
{
String name = "LOTUS";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\xy\\Downloads\\SCA.xls;Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';");
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
From this Blog, there is a Solution with the Clipboard.
Something like this way:
string shapeName = "";
for (int i = 0; i < sheet.Shapes.Count;i++ )
{
Microsoft.Office.Interop.Excel.Shape shape=sheet.Shapes.Item(i);
if (shape.Type == MsoShapeType.msoPicture)
{
shapeName = shape.Name;
}
}
Worksheet sheet = GetFirstSheet();
if (sheet != null)
{
Picture pict = sheet.Pictures(shapeName ) as Picture;
pict.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap);
}
if (Clipboard.ContainsImage())
{
Image img=Clipboard.GetImage();
pbPicture.Image = img;
}

Delete row from datagridview

I having problem on deleting a row of data returned by a search query.
I wish the user can select whichever row of data and click on the delete button [button1_click] to delete it from DB. This is a windows form application.
Hope you can advise me. Thanks a lot.
Below is my code
public partial class Search : Form
{
public Search()
{
InitializeComponent();
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;";
DataTable ds = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM staff", cn))
{
using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
adp.Fill(ds);
comboBox1.DataSource = ds;
comboBox1.ValueMember = "sname";
comboBox1.SelectedIndex = 0;
}
}
}
private void btn_search_bystaffname_Click(object sender, EventArgs e)
{
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;";
DataTable dt = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM booking WHERE sname = #sname", cn))
{
//cmd.Parameters.AddWithValue("#bdate", dtp_search_date.Value.Date);
cmd.Parameters.AddWithValue("#sname", comboBox1.SelectedValue);
using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd))
oda.Fill(dt);
GridView1.DataSource = dt;
GridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[3].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[5].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[0].HeaderText = "Booking ID";
GridView1.Columns[1].HeaderText = "Client Name";
GridView1.Columns[2].HeaderText = "Booking Date";
GridView1.Columns[3].HeaderText = "Booking Time";
GridView1.Columns[4].HeaderText = "Client Contact";
GridView1.Columns[5].HeaderText = "Staff Name";
this.GridView1.DefaultCellStyle.Font = new Font("Times New Roman", 12);
this.GridView1.DefaultCellStyle.ForeColor = Color.Blue;
this.GridView1.DefaultCellStyle.BackColor = Color.Beige;
this.GridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;
this.GridView1.DefaultCellStyle.SelectionBackColor = Color.Black;
this.GridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
}
}
}
private void btn_search_bydate_Click(object sender, EventArgs e)
{
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;";
DataTable dt = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM booking WHERE bdate = #bdate", cn))
{
cmd.Parameters.AddWithValue("#bdate", dtp_search_date.Value.Date);
cmd.Parameters.AddWithValue("#sname", comboBox1.SelectedValue);
using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd))
oda.Fill(dt);
GridView1.DataSource = dt;
GridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[3].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[5].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[0].HeaderText = "Booking ID";
GridView1.Columns[1].HeaderText = "Client Name";
GridView1.Columns[2].HeaderText = "Booking Date";
GridView1.Columns[3].HeaderText = "Booking Time";
GridView1.Columns[4].HeaderText = "Client Contact";
GridView1.Columns[5].HeaderText = "Staff Name";
this.GridView1.DefaultCellStyle.Font = new Font("Times New Roman", 12);
this.GridView1.DefaultCellStyle.ForeColor = Color.Blue;
this.GridView1.DefaultCellStyle.BackColor = Color.Beige;
this.GridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;
this.GridView1.DefaultCellStyle.SelectionBackColor = Color.Black;
this.GridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
GridView1.Rows.Remove(row);
}
}
}
I'm assuming this is the method you want to change
private void button1_Click(object sender, EventArgs e)
{
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
GridView1.Rows.Remove(row);
}
This GridView1.Rows.Remove(row); will only remove the item from the DaDataGridViewRowCollection and will not remove it from the database.
To remove it from the database you can do one of the following
Remove it from `DataTable' and then use a DataAdapter and call update.
Directly delete it from the database using a DELETE SQL statement through a OleDbCommand.
If you choose option one you'd be well served by making dt a Field on your Form. This is because you can only access it now via ((DataRow)row.DataBoundItem).Table or GridView1.DataSource in the button1_Click event. Also making the DataAdapter a field would make this easier
e.g.
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
DataRow dRow = (DataRow)row.DataBoundItem;
dt.Rows.Remove(dRow);
Adapter.Update(dt);
As an aside you can choose to do only the dt.Rows.Remove(dRow); in the button1_Click and defer the Adapter.Update(dt) until later in a Save button.
If you go with option two you'll need to remove it from the DataTable or refresh the DataTable
e.g.
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
OleDbCommand cmd = new OleDbCommand(
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
// not 100% this delete syntax is correct for Access
using (var cmd = new OleDbCommand("DELETE booking WHERE [Booking ID] = #BookingId", cn))
{
cmd.Parameters.AddWithValue("#BookingId", dRow["Booking Id"]);
cmd.ExecuteNonQuery();
}
}
// Do this to update the in-memory representation of the Data
DataRow dRow = (DataRow)row.DataBoundItem;
dt.Rows.Remove(dRow);
// Or just refresh the datatable using code similar as your search methods
Here's how I've been doing it in my application (My unique identifier for the mysql table is in cell zero):
Oh, and dtcommand is a class instance for a database command class I use for common db stuff.
int userDeleteIndex;
if (int.TryParse(datagridview.Rows[rowIndex].Cells[0].Value.ToString(), out userDeleteIndex))
{
if (MessageBox.Show("Delete " + recordidentifyingdata + "? ", "Delete " + userDeleteIndex.ToString(), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
string updateUserSql = "DELETE FROM table WHERE user_id = " + userDeleteIndex.ToString() + "; ";
dtCommand.UpdateTable(updateUserSql);
InitializeUserDataView();
// Initalize userdataview refreshes the datagridview with the updated info
}
catch (Exception err)
{
Error trapping goes here
}
Here's the database update section from my class:
public int UpdateTable(string updateString, string MySqlConnectionString)
{
int returnValue = 0;
MySqlConnection connection = new MySqlConnection(MySqlConnectionString);
MySqlCommand command = new MySqlCommand(updateString, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception err)
{
WriteErrorLog("Unable to update table: " + err.ToString() +
" - Using SQL string: " + updateString + ".");
//MessageBox.Show("An error has occured while updating the database.\n" +
//"It has been written to the file: " + errorFile + ".", "Database Error");
returnValue = -1;
}
finally
{
connection.Close();
}
return (returnValue);
}

Categories