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.
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.
if i add new rows after adding default column value then it shows value , but i want to avoid this if i add then i need to remove this rows , is there any way to handle this
Why column hack shows blank value after adding default value to it?
DataTable myDataTable = new DataTable("HackTable");
myDataTable.Columns.Add("Id");
myDataTable.Columns.Add("Name");
myDataTable.Columns.Add("Address");
myDataTable.Rows.Add(1, "Rahul", "Parel");
myDataTable.Rows.Add(2, "Ramesh", "Dadar");
myDataTable.Rows.Add(3, "Ravi", "Andheri");
DataSet dsT = new DataSet();
dsT.Tables.Add(myDataTable);
dsT.Tables[0].Columns.Add("Hack").DefaultValue = 9999;
System.Data.DataColumn newColumn = new System.Data.DataColumn("Hack", typeof(System.Int32));
newColumn.DefaultValue =9999;
dsT.Tables[0].Columns.Add(newColumn);
Set default value for the column and then add to datatable
DataSet dsT = new DataSet();
DataTable myDataTable = new DataTable("HackTable");
dsT.Tables.Add(myDataTable);
myDataTable.Columns.Add("Id");
myDataTable.Columns.Add("Name");
myDataTable.Columns.Add("Address");
dsT.Tables[0].Columns.Add("Hack").DefaultValue = "9999"; //<-here
myDataTable.Rows.Add(1, "Rahul", "Parel");
myDataTable.Rows.Add(2, "Ramesh", "Dadar");
myDataTable.Rows.Add(3, "Ravi", "Andheri");
DataTable myDataTable = new DataTable("HackTable");
myDataTable.Columns.Add("Id");
myDataTable.Columns.Add("Name");
myDataTable.Columns.Add("Address");
myDataTable.Columns.Add("newColumn");
myDataTable.Columns["newColumn"].DefaultValue = "default";
myDataTable.Rows.Add(1, "Rahul", "Parel");
myDataTable.Rows.Add(2, "Ramesh", "Dadar");
myDataTable.Rows.Add(3, "Ravi", "Andheri");
DataSet dsT = new DataSet();
dsT.Tables.Add(myDataTable);
You have to set default value to column before you insert data.
static void Main(string[] args)
{
DataTable dt = new DataTable("Sample");
dt.Columns.Add("id");
dt.Columns.Add("name");
dt.Columns.Add("Add");
dt.Rows.Add(1, "abc", "hyd");
DataSet ds = new DataSet();
ds.Tables.Add(dt);
DataColumn newColumn = new DataColumn("Hack", typeof(System.String));
newColumn.DefaultValue = "Your Default value";
dt.Columns.Add(newColumn);
string str = "";
}
See snap: IDE Visual Studio DataSet Visualizer.
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"});
I need to add columns to my DataGridView dynamically... to do this here is my code:
dgv.Columns.Clear();
dgv.AutoGenerateColumns = false;
for (int i = 0; i < fields.Length; i++)
{
var newColumn = new DataGridViewColumn(new DataGridViewTextBoxCell());
newColumn.Name = fields[i];
newColumn.DataPropertyName = fields[i];
newColumn.HeaderText = fields[i];
dgv.Columns.Add(newColumn);
}
And after, when I link my query to the DataSource I retrieve this error:
The value can't be null.
Parameter name: columnName
And the strange thing is that here is my DataGridView/DataTable situation:
The names seems right...
The other strange thing is that the first row is shown, but the others gives the exception (the query is OK and the data are valid...)
here is the code to create the DataSource for the table:
public DataTable getData()
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(item.Query, db.getConnection());
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
dap.Fill(ds);
return ds.Tables[0];
}
and after:
dgv.DataSource = getData();
Here is my code, I am trying to display multiplication of Rate * Supply column values and assigning it to the Amount column in data grid view :
try
{
Query = "Select id,Code,Description,Rate,Cust_Id,Supply,Empty,Amount,Received from Items ";
adap = new SQLiteDataAdapter(Query, GlobalVars.conn);
ds = new DataSet();
adap.Fill(ds, "Items");
dtgVOuchers.DataSource = ds.Tables[0];
ds.Tables[0].Columns["Amount"].DefaultValue = (ds.Tables[0].Columns["Rate"].DefaultValue) * (ds.Tables[0].Columns["Supply"].DefaultValue); //error
//dtgVOuchers.Rows.Clear();
ds.Tables[0].Clear();
dtgVOuchers.Refresh();
}
Does anyone know how I can accomplish this functionality in data grid view ? . .Please help me to correct this code. Thanks
just use the query
Select id,Code,Description,Rate,Cust_Id,Supply,Empty,isnull(Rate,0)*isnull(Supply,0) as [Amount],Received from Items
DataTable myDataTable = new DataTable();
DataColumn quantityColumn = new DataColumn("Quantity");
DataColumn rateColumn = new DataColumn("Rate");
DataColumn priceColumn = new DataColumn ("Price");
quantityColumn.DataType = typeof(int);
rateColumn.DataType = typeof(int);
myDataTable.Columns.Add(quantityColumn);
myDataTable.Columns.Add(rateColumn);
myDataTable.Columns.Add(priceColumn);
//Set the Expression here
priceColumn.Expression = "Quantity * Rate";
foreach (DataGridViewRow row in dtgVOuchers.Rows)
{
row.Cells[dtgVOuchers.Columns["Amount"].Index].Value = (Convert.ToDouble(row.Cells[dtgVOuchers.Columns["Rate"].Index].Value) * Convert.ToDouble(row.Cells[dtgVOuchers.Columns["Supply"].Index].Value));
}
Use the below code..run a loop to update the Amount column in all rows
Note : Though this method is not preferred as it effects performance.So do this calculation in the sql query.I dont understand the reason behind not doing the munltiplication in SQL query..
foreach (DataRow row in ds.Tables[0].Rows)
{
row["Amount"]= Convert.ToDecimal(row["Rate"])* Convert.ToDecimal(row["Supply"]);
ds.Tables[0].AcceptChanges();
}
dtgVOuchers.DataSource = ds.Tables[0];
dtgVOuchers.Refresh();