Adding more columns to a datatable in c# - c#

Im trying to read in 3 columns of info (student id, name, subject) into a datatable from a database using a oledb connection. It loads fine and i can get it into a datatable no problem. I then output the datable to a datagridview. Now what i cant figure out how to do is to add 2 more columns after the 3 columns read from the database into the same table and display the now 5 column table to the datagridview. THe two columns of info will come from a list. Can anyone provide an example on how to do this?
Thanks

Now this is heavily abbreviated, and makes many assumptions (i.e. the order of items returned from the query is the same as the order of items in your lists). But this is the basic idea.
string columnFourName = "Col4";
string columnFourName = "Col5";
List<object> columnFourItems = new List<object>()
List<object> columnFiveItems = new List<object>()
SqlConnection oConn = new SqlConnection("SomeConnstring);
oConn.Open();
SqlCommand oComm = new SqlCommand("SELECT * FROM Stuff", oConn);
SqlDataAdapter sda = new SqlDataAdapter(oComm);
DataTable dt = new DataTable();
sda.Fill(dt);
dt.Columns.Add(columnFourName, typeof(object));
dt.Columns.Add(columnFiveName, typeof(object));
for (int row = 0; row < dt.Rows.Count; row++)
{
dt.Rows[row][3] = columnFourItems[row];
dt.Rows[row][4] = columnFiveItems[row];
}

Related

c# wpf sql calculation

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.

How To Add Value To Specified Column In DataTable with SqlCommandBuilder

Several days ago, I just known about SqlCommandBuilder Class. So, Now i try to do CRUD Operation with SqlDataAdapter.Update(DataTable) Method
I had tried this :
I Have Table Named "Student" with 3 Columns, "idstudent","Name","Class"
//Assume We Have Open SqlConnection
//conn = SqlConnection Variabel
SqlCommand cmd = new SqlCommand("SELECT * FROM Student", conn);
SqlDataAdater da = new SqlDataAdater(cmd);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
//Then, I try to insert with SqlDataAdapter.Update(DataTable) Method
dt.Rows.Add('1','AnyName','2');
da.Update(dt);
Finally, My question is how to insert data like below :
dt.Rows.Add
(
'idstudent' => '2',
'Name' => 'Ruka',
'Class' => '3'
);
//Then Finally Update
da.Update(dt);
What i want to do is like Laravel Create() parameters. We say what column we wanted to insert value
I had read about lambda expression but it's not help me to do what i want.
Try this approach
var row = dt.NewRow();
row["idstudent"] = 2;
row["Name"] = "Ruka";
row["Class"] = 3;
dt.Rows.Add(row);
You can also add rows by doing this
dt.Rows.Add(new object[] {"blah", "blah2", "blah3"});

How can I add extra column in datagridview when I fetch data from database

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 store multiple results from a stored procedure into a dataset?

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...

Run time error 'Cannot find column 0'

Run time error Cannot find column 0. below is my code
string connectiostring = (string)ConfigurationSettings.AppSettings["NorthwindConnectionString"];
SqlConnection conn = new SqlConnection(connectiostring);
SqlCommand cmd = new SqlCommand("select * from Employees", conn);
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet data = new DataSet();
adapter.Fill(data,"Employees");
data.Tables["Employees"].Columns.Add("Testcolumn");
DataTable t1 = new DataTable("Employees");
DataRow newrow = t1.NewRow();
newrow[0] = "10";\\this the line i am getting error
newrow[1] = "Pradeep";
newrow[2] = "Kumar";
data.Tables["Employees"].Rows.Add(newrow);
GridView2.DataSource = data;
GridView2.DataBind();
Please help me
Thanks,
You haven't added the columns to the DataTable.
t1.Columns.Add(new DataColumn
{
DataType = string,
ColumnName = "First Name"
});
repeat this for each column supplying the correct type for each.
Create a function that adds columns before trying to add rows.. Call the method at InitializeComponents..
ex.
private void InitTbl(DataTable myTbl)
{
myTbl.Columns.Add(new DataColumn("id"));
myTbl.Columns.Add(new DataColumn("fname"));
myTbl.Columns.Add(new DataColumn("lname"));
}
You need to add some columns to the table first:
DataTable t1 = new DataTable("Employees");
t1.Columns.Add("column1", typeof(string));
t1.Columns.Add("column2", typeof(string));
t1.Columns.Add("column3", typeof(string));
DataRow newrow = t1.NewRow();
...
I think maybe this is actually your problem.
DataTable t1 = new DataTable("Employees")
This creates a brand new table object that is not part of your dataset.
So you should be replace it with this
DataTable t1 = data.Tables["Employees"]
Which gets the table from the dataset and points the t1 variable at that table.

Categories