Merge DataSources in Datagridview - c#

Hello i need to "merge" 2 DataTables in one datagridview and i can't handle it. So far i have sth like this code below and now i want to place another datatable(it have the same number of columns) just below this without any separation(just like adding new rows). For example the code below returns 3 rows so i want my data from another source to appear starting in row 4, how can i do this ? Anyone can help ?
private void button1_Click(object sender, EventArgs e)
{
String name = "Items";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\test.xlsx" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
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;
}

Try this..
Add a new DataTable for another datasource and then add new datarow to first datatable (data)
Then add the columns and relevant data to it.
Do all this after filling first datatable from db.
take reference from this
http://www.codeproject.com/Questions/670856/how-to-add-new-row-and-new-values-in-gridview-in-a

Related

Updating excel values in data grid view on certain condition

I need to fetch a row value from an excel sheet in data grid view in winform.
I’m able to display the entire excel sheet in the datagridview. But, I need to display particular rows in the grid based on a current date condition.
public DataTable ReadExcel2(string fileName, string fileExt)
{
string connectionstring ;
DataTable dtexcel2 = new DataTable();
connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand oconn = new OleDbCommand("Select * From [POSFailures$] WHERE Date=#date");
oconn.Connection = connection;
try
{
oconn.Parameters.AddWithValue("#date", DateTime.Now.ToString("MM/dd/yyyy"));
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}
return dtexcel2;
}
Thanking you in advance
What seems to be happening here is that the Date parameter is not being honored, as you are getting back all of the rows. So, I used Google to figure out how to properly add parameters when using OleDbConnection. I found this:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement
Source: https://learn.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbcommand.parameters?redirectedfrom=MSDN&view=netframework-4.8#System_Data_OleDb_OleDbCommand_Parameters
Using the example on that page, try changing your code to this:
string connectionstring;
DataTable dtexcel2 = new DataTable();
connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand command = new OleDbCommand("Select * From [POSFailures$] WHERE Date = ?");
command.Parameters.Add(new OleDbParameter(DateTime.Now.ToString("MM/dd/yyyy"), OleDbType.Date));
command.Connection = connection;
try
{
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(command);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}
Please note that i've not tested this, so I can't promise it will work. But, the main point is... the answer is out there! You just need to go looking for it.

How to Update data in the dataGridview ONLY

My application imports a sheet from an excel file with only the header column names into a new dataGridView Table. To keep it easy lets say the Column names are; Name, City, State, Status. I "hard code" the first 2 entries as Jack, Detroit, MI, Missing; and Mike, Chicago, IL, Missing. Next I import an XML file that adds more entries. I have the code looking for the original 2 entries, if found, I want it to "update" or "re-edit" the Missing to Found. (I want this to happen ONLY in the dataGridView Table. The sql examples I'm finding are all aimed at updating the original database. I want it to only update the dataGridView table.
This code is designed to update the excel file.
sql = "UPDATE " + myNameRange + " SET " + mySET + "' WHERE " + myWHERE + "'";
Is there a way I can do something like this only to change the data in the dataGridView?
Method to bring in sheets from excel
public static void loadData(string SheetName, DataGridView MyDataGrid, string filePathMain)
{
string pathCon = "Provider=Microsoft.Ace.OLEDB.12.0; Data Source=" + filePathMain + ";Extended Properties=\"Excel 8.0; HDR=YES;IMEX=3;READONLY=FALSE\";";
OleDbConnection conn = new OleDbConnection(pathCon);
OleDbCommand cmd = new OleDbCommand("select * from [" + SheetName + "]", conn);
conn.Open();
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
//MessageBox.Show( dt.Rows.Count.ToString());
MyDataGrid.Tag = dt.Rows.Count.ToString();
MyDataGrid.DataSource = dt;
OleDbCommand updateCmd = new OleDbCommand("UPDATE [" + SheetName + "]");
myDataAdapter.UpdateCommand = updateCmd;
conn.Close();
}
Here I'm hard coding the data into the table. This works.
DataTable dt = ((DataGridView)TC).DataSource as DataTable;
DataRow row0 = dt.NewRow();
row0["Name"] = "Jack";
row0["Status"] = "MISSING";
dt.Rows.Add(row0);
DataRow row1 = dt.NewRow();
row1["Name"] = "Mike";
row1["Status"] = "MISSING";
dt.Rows.Add(row1);
dgvThing.DataSource will give you the data that is bound to your DataGridView and you can minipulate this without modifying your original data source i.e. the excel file.
Edit: In this case, you would loop through the rows to find your person and update their status like so.
DataTable dt = ((DataGridView)TC).DataSource as DataTable;
foreach (DataRow row in dt.Rows)
{
if (row["Name"].Equals("Jack"))
row["Status"] = "Found";
}

Apply a TableStyle to a QueryTable

I can use a query table:
var sheet = (_excel.ActiveSheet as Excel.Worksheet);
var rng = sheet.Range("A1");
var qt = sheet.QueryTables.Add("ODBC;...", rng, "SELECT * FROM myTable");
qt.Refresh();
and this will import the data correctly (e.g. dates actually display as dates etc...). But when I try and access the ListObject to apply a TableStyle I get an exception.
Now if I add a list object like:
var sheet = (_excel.ActiveSheet as Excel.Worksheet);
var qt = sheet.ListObjects.Add(
Excel.Enums.XlListObjectSourceType.xlSrcQuery,
"ODBC;...",
null,
Excel.Enums.XlYesNoGuess.xlNo,
rng,
"TableStyleMedium9").QueryTable;
qt.CommandType = Excel.Enums.XlCmdType.xlCmdSql;
qt.CommandText = "SELECT * FROM myTable";
qt.Refresh();
The the dates in the query display as decimal numbers and not dates...
I could just format the columns afterwards, but the problem is that I won't actually know the query that is being run as the user types this at runtime, so I would prefer to get Excel to do this.
So essentially, what I want, is to use the first bit of code and apply a TableStyle to it.
Can anyone help?
This doesn't do coloring, but it does organize the data into a datatable, and when you're debugging with breakpoints and mouse over the datatable after its been filled you can see all the data organized into columns. What you can then do with the datatable is bind it to a datagrid view on your win forms element.
I have this DataTable DataTable = new DataTable(); as a global field at the top.
OleDbConnection conn = new OleDbConnection();
//This is making a connection to the excel file, don't worry about this I think you did it differently.
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + stringFileName + ";" + "Extended Properties=\"Excel 12.0;HDR=Yes;\""; OleDbCommand cmd = new OleDbCommand
("SELECT * FROM [" + sheetFromTo + "]", conn);
DataSet dataSet1 = new DataSet();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(cmd);
try
{
conn.Open();//opens connection
dataSet1.Clear();//empties, incase they refill it later
dataAdapter.SelectCommand = cmd;//calls the cmd up above
dataAdapter.Fill(dataSet1);//fills the dataset
dataGridView1.DataSource = dataSet1.Tables[0];//puts the dataset in the dataGridview
//important** creates a datatable from the dataset, most of our work with the server is with this datatable
DataTable dataTable = dataSet1.Tables[0];
DataTable = dataTable;
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}

Update entire Excel table with OleDb

My excel simulation needs to be imported into C#, after which the table needs to be able to be refreshed. The simulation revolves around randomly generated numbers. The random numbers are the only columns that change, since I'm doing that manually. The surrounding columns should update with the random numbers. I have tried various things but no luck so far.
Also, as the code is now, the
adp.Update(excelDataSet);
command invokes the error "Update requires a valid UpdateCommand when passed DataRow collection with modified rows." The table is only loaded into the gridview at all when it is commented out.
Here is my code atm. Thanks in advance.
string fileName = #"C:\simulation.xlsx";
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;READONLY=FALSE\"";
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
con.Open();
OleDbCommand selectCommand = new OleDbCommand("select * from [SHEET1$]", con);
OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter();
adp.SelectCommand = selectCommand;
DataSet excelDataSet = new DataSet();
adp.Fill(excelDataSet);
for (int i = 0; i < 29; i++)
{
excelDataSet.Tables[0].Rows[i][1] = Math.Round(r.NextDouble(), 2);
excelDataSet.Tables[0].Rows[i][6] = Math.Round(r.NextDouble(), 2);
excelDataSet.Tables[0].Rows[i][8] = Math.Round(r.NextDouble(), 2);
}
adp.Update(excelDataSet);
gridview.DataSource = excelDataSet.Tables[0];
con.Close();
Add a line that build a OleDbCommandBuilder
....
OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter();
adp.SelectCommand = selectCommand;
OleDbCommandBuilder cb = new OleDbCommandBuilder(adp);
adp.UpdateCommand = cb.GetUpdateCommand();
....
This will create the UpdateCommand in the OleDbDataAdapter for you, (can be used also for the InsertCommand and DeleteCommand)

Import Excel trough OleDbDataAdapter in C# With changing Column names

Hello well i try to import a Excel document into my DataGridView in C#.
So far it worked but there is a Column with Data in it i need to 'sort'.
If this was simple i would do "WHERE test > 0" in the OleDbDataAdapter query.
But.. The name of the Column is changing with each document and i need to use it often. So far i got this :
private void button1_Click(object sender, EventArgs e)
{
String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\Users\\Test\\Desktop\\Test.xls;" +
"Extended Properties=Excel 8.0;";
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Test$]", strConn);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
In the select i need to put a line witch state that the first 3 letters of the column is the same but the number that follow are not. Like:
QTA 12345,
QTA 13213,
QTA 92818.
Something like:
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Test$] WHERE [testColumn] > 0", strConn);
But then with the same first 3 letters and the last numbers who are random.
Can someone help me please?
I've tried some code and it works fine for me. Have a try:
OleDbConnection oleDbConnection = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=D:\\Users\\name\\Desktop\\test.xls;" +
"Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");
oleDbConnection.Open();
//Get columns
DataTable dtColumns = oleDbConnection.GetSchema("Columns", new string[] { null, null, "Tabelle1$", null });
List<string> columns = new List<string>();
foreach (DataRow dr in dtColumns.Rows)
columns.Add(dr[3].ToString());
string colName = columns.Find(item => item.Substring(0,3) == "QTA");
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Tabelle1$] WHERE [" + colName + "] > 0", oleDbConnection);
da.Fill(ds);
dataGrid1.ItemsSource = ds.Tables[0].DefaultView;
oleDbConnection.Close();
Pay attention to changing the connection string to your needs.
You can trim the code, using LINQ:
string colName = (from DataRow dr in dtColumns.Rows where dr[3].ToString().Substring(0, 3) == "QTA" select dr[3].ToString()).ElementAt(0);

Categories