Hi so I've only just began creating a exam scheduling system and I have an issue when inserting a Excel table into my data grid view. I've created some rows and columns for time however when i insert new data it pads with empty cells and inserts below instead of going into the existing ones. Any help is appreciated.
string PathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtPath.Text + ";Extended Properties=\"Excel 8.0; HDR = Yes;\";";
OleDbConnection MyConnection = new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", MyConnection);
DataTable dt = new DataTable();
dt.Columns.Add("Time");
DataRow dr = dt.NewRow();
dr["Time"] = "9:00";
dt.Rows.Add(dr);
DataRow dr1 = dt.NewRow();
dr1["Time"] = "10:00";
dt.Rows.Add(dr1);
`etc`
myDataAdapter.Fill(dt);
DataGridView1.DataSource = dt;
It is unclear what you are trying to achieve. In reference to the posted code, you are correct that the table will have “empty” cells for the top two rows except for the first column with the “9:00 and 10:00” values. In addition, there will be “empty” cells in the first column after the first two rows. This is because you are adding the columns AND rows for the “time” values “BEFORE” you are filling it with the data.
I recommend you ADD the data FIRST, then add the “time” column. Then instead of “adding” new rows for the time values… use the “existing” rows that are there from when you read the original data.
Example: first fill the table with the data… myDataAdapter.Fill(dt);… then add the “time” column as the first column in the existing table. It may look something like…
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", MyConnection);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
DataColumn timeCol = new DataColumn("Time", typeof(string));
dt.Columns.Add(timeCol);
timeCol.SetOrdinal(0);
dt.Rows[0].SetField("Time", "9:00");
dt.Rows[1].SetField("Time", "10:00");
dataGridView1.DataSource = dt;
Related
i am working with an application(c# wpf, sql)
What i want to do with this program is that when i retrieve data from SQL database( Product, Price , qty) and show in datagrid the program should update automatically the column named total
The code I used to retrieve data is shown below
SqlCommand cmd = new SqlCommand("SELECT * From evid", conn);
DataTable dt = new DataTable("dtList");
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dtg.ItemsSource = dt.DefaultView;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
conn.Close();
And the code i used to do the calculation is shown bleow:
int a = Convert.ToInt32(dtg.Columns[0]);
int b = Convert.ToInt32(dtg.Columns[1]);
int c = Convert.ToInt32(dtg.Columns[2]);
c = a * b;
I also want that from example when i update the column quantity from 1 to 2 ; the column total should update itself
Thanks to everyone
It would probably be easier, rather than attempting to calculate the new columns data on c#, to do it in the SQL query.
Firstly this will be less stressful on the system than having to calculate multiple rows of variables, secondly it will be more efficient code-wise.
c = a * b; //This assumed that those two columns are simply variables, which is not how DataTable rows work.
In your sql, according to the information you provided, I recommend something along these lines:
SELECT
Product,
Price,
Quantity,
SUM(Price * Quantity) as Calculation
FROM
evid
GROUP BY
Product,
Price,
Quantity
This SQL query would go into your SqlCommand:
SqlCommand cmd = new SqlCommand("--Query above--", conn);
From there you can simply add the calculation as a new datatable column.
UPDATE
Apologies everyone, I misread the question. You made me curious about figuring a solution to this problem. I whipped up some code which solves the issue you have and will explain as below:
Firstly in order to make it work I had to change your method of filling the table, using DataGrid.Fill(DataTable) wouldn't work as I had to use a custom expression as a data source.
I handled this all programatically for the sake of easy readability, however this should be easy enough to convert to WPF if you wish.
The code:
SqlConnection sqlConn = new SqlConnection("server = ServerName; " + "Trusted_Connection = yes; " + "database = ReportPool; " + "connection timeout = 120");//Sql connection
SqlCommand sqlCmd = new SqlCommand(String.Format("SELECT {0} FROM {1}",//SQl command
"Product, Price, Quantity",
"ReportPool.dbo.TestTable"
), sqlConn);
DataTable dataTable = new DataTable();//Created a new DataTable
DataColumn dc = new DataColumn();//Made a new DataColumn to populate above DataTable
dc.DataType = System.Type.GetType("System.String");//Defined the DataType inside, this can be [[int]] if you want.
dc.ColumnName = "Product";//Gave it a name (important for the custom expression - can only be one word so use underscores if you need multiple words)
DataColumn dc2 = new DataColumn();
dc2.DataType = System.Type.GetType("System.Decimal");
dc2.ColumnName = "Price";
DataColumn dc3 = new DataColumn();
dc3.DataType = System.Type.GetType("System.Decimal");
dc3.ColumnName = "Quantity";
DataColumn dc4 = new DataColumn();
dc4.DataType = System.Type.GetType("System.Decimal");
dc4.ColumnName = "CalculatedColumn";
dc4.Expression = "Price * Quantity";//Multiplying the Price and Quantity DataColumns
dataTable.Columns.Add(dc);//Add them to the DataTable
dataTable.Columns.Add(dc2);
dataTable.Columns.Add(dc3);
dataTable.Columns.Add(dc4);
dataGridControl.ItemsSource = dataTable.DefaultView;//Set the DataGrid ItemSource to this new generated DataTable
sqlConn.Open();//Open the SQL connection
SqlDataReader reader = sqlCmd.ExecuteReader();//Create a SqlDataReader
while (reader.Read())//For each row that the SQL query returns do
{
DataRow dr = dataTable.NewRow();//Create new DataRow to populate the DataTable (which is currently binded to the DataGrid)
dr[0] = reader[0];//Fill DataTable column 0 current row (Product) with reader[0] (Product from sql)
dr[1] = reader[1];
dr[2] = reader[2];
dataTable.Rows.Add(dr);//Add the new created DataRow to the DataTable
}
Hopefully you can now solve the issue you've been experiencing, feel free to comment if you need any help interpreting this code or just need more assistance.
Apologies for the late update.
I read data from excel into datagridview in C#. I want to assign row in excel (example 10) to Column Name in datagridview. Code below default get first row in excel.
using (OleDbConnection connExcel = new OleDbConnection(connString))
{
string selectString = #"Select * from [" + comboBox1.SelectedValue.ToString() + "]";
using (OleDbCommand cmdExcel = new OleDbCommand(selectString, connExcel))
{
cmdExcel.Connection = connExcel;
connExcel.Open();
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter();
adp.SelectCommand = cmdExcel;
adp.FillSchema(dt, SchemaType.Source);
adp.Fill(dt);
dataGridView2.DataSource = dt;
}
}
You will have to do it programmatically. In your code, the adp.FillSchema(dt, SchemaType.Source); is implicitly pulling the column names from the spreadsheet, but not the data. You follow it with adp.Fill(dt); which does the same thing with the data.
To do it programmatically, you need to read row 10 using a OleDbDataReader.Get() and assign each Excel cell to the DataGridView column header that matches.
DataRow newRow = dt.New
newRow[1] = dr.xxx
newRow[2] = dr.xxx
newRow[3] = dr.xxx
newRow[4] = dr.xxx
newRow[5] = dr.xxx
newRow[6] = dr.xxx
newRow[7] = dr.xxx
newRow[8] = dr.xxx
dt.Rows.Add(newRow);
You will then need to do the rest of the rows of data the same way in a loop. A link to an article that is more specific is Populate a DGV from a DR. The bottom half covers what you need to do.
I am using datagridview as in pic
column named ID has combobox . and DGV bounded with database using Data Table .
working is as following :-
when I select value from combobox in row 1 , then it display data in corresponding rows(i.e row 1) .
Issue :-
When I select value from combobox in row 2 , it does not display data in row 2 ,but shows it data in row 1 (i.e replacing earlier data in row 1).
how I can display data in row 2 and similarly for all other rows keeping the data selected in previous rows safe .....
how combobox is getting filled :-
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "SELECT id FROM dgvdata";
System.Data.SqlClient.SqlDataAdapter sqlDataAdap = new System.Data.SqlClient.SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.ValueMember = "id";
con.Close();
how datagridview filled on selection on combobox :-
con.Open();
string sql = "select time,PARTY_NAME , DATE from dgvdata where id ='" + comboBox1.Text + "'";
System.Data.SqlClient.SqlDataAdapter dataadapter = new System.Data.SqlClient.SqlDataAdapter(sql, con);
DataTable dt = new DataTable();
dataadapter.Fill(dt);
dataGridView1.DataSource = dt;
con.close();
thanks in advance..
In my database I have 4 column. I fetch this database value in a datagridview. But I want to add two columns in datagridview. So, I want to make a datagridview with 6 columns. Within this 6 columns 4 columns will filled by database value. How can I do this?
OleDbConnection con = new OleDbConnection("CONNECTION STRING");
con.Open();
DataTable dtusers = new DataTable();
OleDbCommand cmd = new OleDbCommand("Select Code,Description,Qnty,Rate from PurchaseTable'", con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dtusers);
dataGridView1.DataSource = dtusers;
dataGridView1.Columns[0].Name = "Code ";
dataGridView1.Columns[1].Name = "Description";
dataGridView1.Columns[2].Name = "Qnty";
dataGridView1.Columns[3].Name = "Rate";
con.Close();
Here are 4 columns. Code,Description,Qnty,Rate. I want to add two more columns in this datagridview. Amount and Narration. But Amount and Narration columns are not present in PurchaseTable.How can I do this?
If you want blank columns then create them and insert. If the data is in the database then add a join to your query to retrieve the data.
Adding blank columns
DataGridView dgv = new DataGridView();
dgv.DataSource = dtusers;
DataGridViewColumn amount = new DataGridViewColumn();
amount.HeaderText = "Amount";
amount.Name = "Amount";
dgv.Columns.Insert(0, amount);
DataGridViewColumn narration = new DataGridViewColumn();
narration.HeaderText = "Narration";
narration.Name = "Narration";
dgv.Columns.Insert(0, narration);
Assumed that you already have dtusers ..
Do Column adding to dtuser .. http://msdn.microsoft.com/en-us/library/hfx3s9wd.aspx
Do looping for all rows in your table to fill your new column
Assign the table as dgv datasource .. dataGridView1.DataSource = dtusers;
Because your column names are hardcoded, I think you can create a predefined columns in your datagridview through designer(Click datagridview -> choose Edit Columns).
Create all 6 columns you want. On the first four set DataPropertyName to name of the column from your query. Last two leave empty.
And remember set datagridview.AutoGeneratedColumns = false; before you binding data to datagridview...(somewhere in form_Load handler)
After this your code will be:
using (OleDbConnection con = new OleDbConnection("CONNECTION STRING"))
{
con.Open();
DataTable dtusers = new DataTable();
using(OleDbCommand cmd = new OleDbCommand("Select Code,Description,Qnty,Rate from PurchaseTable'", con))
{
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dtusers);
dataGridView1.DataSource = dtusers;
}
con.Close();
}
How do I combine to result sets from a StoredProcedure into one dataset in ASP.NET?
Below is my code in asp.net
SqlDataAdapter adap = new System.Data.SqlClient.SqlDataAdapter("sp_Home_MainBanner_TopStory",con);
adap.SelectCommand.CommandType = CommandType.StoredProcedure;
adap.SelectCommand.Parameters.AddWithValue("#rows", 9);
DataSet DS = new DataSet();
adap.Fill(DS, "Table1");
adap.Fill(DS, "Table2");
GridView1.DataSource = DS.Tables["Table2"];
GridView1.DataBind();
Even if there were two adapters, how could I combine the results into one dataset?
In MS SQL we create a procedure like:
[ create proc procedureName
as
begin
select * from student
select * from test
select * from admin
select * from result
end
]
In C#, we write following code to retrieve these values in a DataSet
{
SqlConnection sqlConn = new SqlConnection("data source=(local);initial catalog=bj001;user id=SA;password=bj");
SqlCommand sqlCmd = new SqlCommand("procedureName", sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConn.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlCmd);
DataSet ds = new DataSet();
sda.Fill(ds);
sqlconn.Close();
// Retrieving total stored tables from a common DataSet.
DataTable dt1 = ds.Tables[0];
DataTable dt2 = ds.Tables[1];
DataTable dt3 = ds.Tables[2];
DataTable dt4 = ds.Tables[3];
// To display all rows of a table, we use foreach loop for each DataTable.
foreach (DataRow dr in dt1.Rows)
{
Console.WriteLine("Student Name: "+dr[sName]);
}
}
A DataSet contains Tables. For your above example, if you had two SqlDataAdapters, each calling a stored procedure and stored them like you did above.
adapter1.Fill(DS, "Table1");
adapter2.Fill(DS, "Table2");
This will take the table results from your first query and store it in the DataSet DS as Table1. It will then store another Table (Table2) in the same DataSet. To access these tables you use the following code:
DS.Tables["Table1"] //Or Table2, or whatever you name it during your Fill.
You already have the right process, you just need to look up how a DataSet works and decide how you want to call your information.
IF you want to combine your results into one DataTable however, you will need to iterate through the tables and combine information.
ex:
DataTable combinedTable = new DataTable();
//Create columns
foreach (DataRow row in DS.Tables["Table1"].Rows)
{
//Create rows? Copy information over? Whatever you want to do.
}
try using this:
adapter1.Fill(DS, "Table1, Table2");
this works here so...