How add row to gridview in WPF using C# - c#

How add rows to grid-view in WPF,when the grid-view already contains the data.,
SqlCommand cmd = new SqlCommand("SELECT CName'Name',CLocation'Location',VehicleNo,GasName,Quantity,OrderDate,SupplyDays'Dispatching Day' FROM View_DailyPlanning "
+ " where (OrderDate='" + DateTime.Now.ToShortDateString() + "' and SupplyDays='" + day + "')", DataAccessBase.GetSqlConnection());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("View_DailyPlanning");
da.Fill(dt);
grid_display.AutoGenerateColumns = true;
grid_display.ItemsSource = dt.DefaultView;
grid_display.Columns[0].Width = 100;
grid_display.Columns[1].Width = 150;
grid_display.Columns[2].Width = 100;
grid_display.Columns[3].Width = 100;
grid_display.Columns[4].Width = 100;
grid_display.Columns[5].Width = 100;
grid_display.Columns[6].Width = 100;
grid_display.Items.Add(new Item() { CName = "Someone4", CLocation = "Madivala",VehicleNo="TN2345",Quantity="26",Date="10/07/2014",SupplyDays="Friday"});
ction());
SqlCommand cmd = new SqlCommand("SELECT CName'Name',CLocation'Location',VehicleNo,GasName,Quantity,OrderDate,SupplyDays'Dispatching Day' FROM View_DailyPlanning "
+ " where (OrderDate='" + DateTime.Now.ToShortDateString() + "' and SupplyDays='" + day + "')", DataAccessBase.GetSqlConnection());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("View_DailyPlanning");
da.Fill(dt);
grid_display.AutoGenerateColumns = true;
grid_display.ItemsSource = dt.DefaultView;
grid_display.Columns[0].Width = 100;
grid_display.Columns[1].Width = 150;
grid_display.Columns[2].Width = 100;
grid_display.Columns[3].Width = 100;
grid_display.Columns[4].Width = 100;
grid_display.Columns[5].Width = 100;
grid_display.Columns[6].Width = 100;
grid_display.Items.Add(new Item() { CName = "Someone4", CLocation = "xxx",VehicleNo="1234",Quantity="26",Date="10/07/2014",SupplyDays="Friday"});
How to add additional rows to grid-view,any ideas for do this.,

So from scratch, you can add new rows with the following code
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("ColumnA", typeof(string));
dt.Columns.Add("ColumnB", typeof(string));
}
DataRow NewRow = dt.NewRow();
NewRow[0] = "Some Text";
NewRow[1] = "Some Other Text";
dt.Rows.Add(NewRow);
GridView1.DataSource = dt;
GridViewl.DataBind();
To add additional rows use
DataRow NewRow = dt.NewRow();
I hope this helps

Related

Datagridview to display combobox on form load

I have the below code which fills the datagridview's first 2 columns with comboboxes and the rest wit textboxes.
In which datagridview event should the below code be added so that the comboxboxes are displayed on form load?
I have tried cellbeginedit,cellclick, cellvaluechanged but all these execute the code on cell event change:
try
{
// Bind grid cell with combobox and than bind combobox with datasource.
DataGridViewComboBoxCell l_objGridDropbox = new DataGridViewComboBoxCell();
if (e.ColumnIndex == 0)
{
DgvVchentry[e.ColumnIndex, e.RowIndex] = l_objGridDropbox;
l_objGridDropbox.DataSource = DrCr();
l_objGridDropbox.ValueMember = "DrCr";
l_objGridDropbox.DisplayMember = "DrCr";
using (OleDbConnection con = new OleDbConnection(ApplicationSettings.Connectionstring()))
{
// Check the column cell, in which it click.
if (CmbTxnType.Text == "Receipt")
{
if (DgvVchentry.Rows[e.RowIndex].Cells[0].Value.Equals("Dr"))
{
// On click of datagridview cell, attached combobox with this click cell of datagridview
DgvVchentry[e.ColumnIndex, e.RowIndex] = l_objGridDropbox;
DataTable l_dtDescription = new DataTable();
string query = "select lname from tbl_ledger where subgrp='Bank' and socno=" + frmsocdetails.socid + " or subgrp='Cash' and socno=" + frmsocdetails.socid + "";
OleDbDataAdapter sda = new OleDbDataAdapter(query, con);
sda.Fill(l_dtDescription);
l_objGridDropbox.DataSource = l_dtDescription;
l_objGridDropbox.ValueMember = "LNAME";
l_objGridDropbox.DisplayMember = "LNAME";
}
else
{
DgvVchentry[e.ColumnIndex, e.RowIndex] = l_objGridDropbox;
DataTable l_dtDescription = new DataTable();
string query = "select lname from tbl_ledger where socno=" + frmsocdetails.socid + " and subgrp<>'Bank' and subgrp<>'Cash'";
OleDbDataAdapter sda = new OleDbDataAdapter(query, con);
sda.Fill(l_dtDescription);
l_objGridDropbox.DataSource = l_dtDescription;
l_objGridDropbox.ValueMember = "LNAME";
l_objGridDropbox.DisplayMember = "LNAME";
}
}
else if (CmbTxnType.Text == "Payment")
{
if (DgvVchentry.Rows[e.RowIndex].Cells[0].Value.Equals("Cr"))
{
// On click of datagridview cell, attched combobox with this click cell of datagridview
DgvVchentry[e.ColumnIndex, e.RowIndex] = l_objGridDropbox;
DataTable l_dtDescription = new DataTable();
string query = "select lname from tbl_ledger where subgrp='Bank' and socno=" + frmsocdetails.socid + " or subgrp='Cash' and socno=" + frmsocdetails.socid + "";
OleDbDataAdapter sda = new OleDbDataAdapter(query, con);
sda.Fill(l_dtDescription);
l_objGridDropbox.DataSource = l_dtDescription;
l_objGridDropbox.ValueMember = "LNAME";
l_objGridDropbox.DisplayMember = "LNAME";
}
else
{
l_objGridDropbox.Items.Clear();
DgvVchentry[e.ColumnIndex, e.RowIndex] = l_objGridDropbox;
DataTable l_dtDescription = new DataTable();
string query = "select lname from tbl_ledger where socno=" + frmsocdetails.socid + " and subgrp<>'Bank' and subgrp<>'Cash'";
OleDbDataAdapter sda = new OleDbDataAdapter(query, con);
sda.Fill(l_dtDescription);
l_objGridDropbox.DataSource = l_dtDescription;
l_objGridDropbox.ValueMember = "LNAME";
l_objGridDropbox.DisplayMember = "LNAME";
}
}
else
{
DgvVchentry[e.ColumnIndex, e.RowIndex] = l_objGridDropbox;
DataTable l_dtDescription = new DataTable();
string query = "select lname from tbl_ledger where socno=" + frmsocdetails.socid + "";
OleDbDataAdapter sda = new OleDbDataAdapter(query, con);
sda.Fill(l_dtDescription);
l_objGridDropbox.DataSource = l_dtDescription;
l_objGridDropbox.ValueMember = "LNAME";
l_objGridDropbox.DisplayMember = "LNAME";
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Updating cells using dataset read from xls file and save to CSV file

can somebody tell me why this update procedure doesn't work? I want to read data to dataset from XLS and it works just fine but UPDATE doesn't work at all. No errors, no changes, like it doesn't exist. The file creates but values are just a copy from original xls.
Xls sheet format is pretty simple, one column: id 1 2 3
string string_conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\name.xls;Extended Properties='Excel 8.0;HDR=Yes;'";
OleDbConnection conn = new OleDbConnection(string_conn);
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
comboBox1.DataSource = excelSheets;
string xlsSheet = comboBox1.SelectedItem.ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
adapter.UpdateCommand = new OleDbCommand ("UPDATE " + xlsSheet + " SET id = " + tbox1.Text + " WHERE id = " + tbox2.Text + "", conn);
adapter.UpdateCommand.Parameters.Add("#id", OleDbType.Char, 255).SourceColumn = "id";
adapter.UpdateCommand.Parameters.Add("#Oldid", OleDbType.Char, 255, "id").SourceVersion = DataRowVersion.Original;
adapter.Update(dataset);
dataset.AcceptChanges();
DataTable dtable = new DataTable();
dtable = dataset.Tables[0];
StringBuilder str = new StringBuilder();
foreach (DataRow dr in dtable.Rows)
{
foreach (var field in dr.ItemArray)
{
str.Append(field.ToString());
str.Append(", ");
}
str.Replace(",", str.AppendLine().ToString(), str.Length - 1, 1);
}
MessageBox.Show(str.ToString()); //for test's sake
string pathFile = #"path\filename.csv";
if (!File.Exists(pathFile))
{
File.Create(pathFile).Close();
}
File.AppendAllText(pathFile, str.ToString());
Something is wrong with parameters probably but I tried this way and also no go (I added 2nd column so id stays the same just to find proper row), I get UPDATE command syntax error on execute:
string string_conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\arkusz.xls;Extended Properties='Excel 8.0;HDR=Yes;'";
OleDbConnection conn= new OleDbConnection(string_conn);
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
comboBox1.DataSource = excelSheets;
string xlsSheet = comboBox1.SelectedItem.ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
adapter.UpdateCommand = new OleDbCommand("UPDATE " + xlsSheet + " SET nazwa = #nazwa WHERE id = #id", conn);
adapter.UpdateCommand.Parameters.AddWithValue("#id", tbox1.Text).OleDbType = OleDbType.Integer;
adapter.UpdateCommand.Parameters.AddWithValue("#nazwa", tbox2.Text).OleDbType = OleDbType.VarChar;
adapter.UpdateCommand.ExecuteNonQuery();
adapter.Update(dataset);
dataset.AcceptChanges();
DataTable dtable = new DataTable();
dtable = dataset.Tables[0];
StringBuilder str = new StringBuilder();
foreach (DataRow dr in dtable.Rows)
{
foreach (var field in dr.ItemArray)
{
str.Append(field.ToString());
str.Append(", ");
}
str.Replace(",", str.AppendLine().ToString(), str.Length - 1, 1);
}
MessageBox.Show(str.ToString());
string sciezkaPlik = #"path\filename.csv";
if (!File.Exists(sciezkaPlik))
{
File.Create(sciezkaPlik).Close();
}
File.AppendAllText(sciezkaPlik, str.ToString());
I solved the issue. For future reference it works well like this:
string string_conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\arkusz.xls;Extended Properties='Excel 8.0;HDR=Yes;'";
OleDbConnection conn = new OleDbConnection(string_conn);
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
comboBox1.DataSource = excelSheets;
string xlsSheet = comboBox1.SelectedItem.ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
OleDbCommand odbc = new OleDbCommand("UPDATE ["+xlsSheet+"] SET nazwa = " + txtNewValue.Text + " WHERE id = " + txtID.Text + "", conn);
adapter.UpdateCommand = odbc;
odbc.Parameters.AddWithValue("nazwa", txtNewValue.Text).OleDbType = OleDbType.VarChar;
odbc.Parameters.AddWithValue("id", txtID.Text).OleDbType = OleDbType.Integer;
odbc.ExecuteNonQuery();
dataset.Clear();
adapter.Fill(dataset);
DataTable dtable = new DataTable();
dtable = dataset.Tables[0];
StringBuilder str = new StringBuilder();
foreach (DataRow dr in dtable.Rows)
{
foreach (var field in dr.ItemArray) /
{
str.Append(field.ToString());
str.Append(", ");
}
str = str.Replace(',', '\n');
}
string filePath= #"path\filename.csv";
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
File.WriteAllText(filePath, str.ToString());
EDIT - I think it may be that this line needs to have the parameters put in as a question mark instead of having the actual values passed in, so more like this:
adapter.UpdateCommand = new OleDbCommand ("UPDATE " + xlsSheet + " SET id = ? WHERE id = ?", conn);
Then your next couple of lines are correct, they are clever enough to replace the question marks from the UpdateCommand with the actual values at run time:
adapter.UpdateCommand.Parameters.Add("#id", OleDbType.Char, 255).SourceColumn = "id";
adapter.UpdateCommand.Parameters.Add("#Oldid", OleDbType.Char, 255, "id").SourceVersion = DataRowVersion.Original;
Hare is a very simple method to do an insert into an Excel sheet.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [Sheet1$] (id,name) values('5','e')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

Loop inside loop for .Net C#

I want to retrieve all User_id's next after my entered User_id referencing each other from the table by Reference_id, the code below gives the exact result but it retrieves all User_id's from "2001 to 2005".
I want if i enter the "2002" as User_id from a textbox then it must retrieve from "2003 - 2005"
Table_xyz column User_id have value= 2001, 2002, 2003, 2004, 2005
Table_xyz column Reference_id have value= 2000, 2001, 2002, 2003, 2004
var gCmd = new SqlCommand(#"SELECT User_id FROM Table_xyz", nCon);
SqlDataAdapter Sda = new SqlDataAdapter(gCmd);
DataTable Dt = new DataTable();
Sda.Fill(Dt);
for (int i = 0; i < Dt.Rows.Count; i++)
{
string referenceid = Dt.Rows[i]["User_id"].ToString();
var gCmd1 = new SqlCommand(#"SELECT User_id FROM Table_xyz
WHERE Reference_id = '" + referenceid + "'", nCon);
SqlDataAdapter Sda1 = new SqlDataAdapter(gCmd1);
DataTable Dt1 = new DataTable();
Sda1.Fill(Dt1);
Response.Write(referenceid);
}
I tried adding "SELECT User_id FROM Table_xyz WHERE User_id = '2001'" to the first command but it returns only a single value where User_id matched "2001"
This is the easiest solution. But consider refactoring your code or thinking on another approach, this is not perfomatic. Also consider using parameters on you sql command.
string initialId = Dt.Rows[0]["ID"].ToString();
do
{
string dCmd = "SELECT ID FROM TableA WHERE Reference_ID = '" + initialId + "'";
SqlDataAdapter dSda = new SqlDataAdapter();
dSda.SelectCommand = new SqlCommand(dCmd, nCon);
DataTable dDt = new DataTable();
dSda.Fill(dDt);
for (int i = 0; i < dDt.Rows.Count; i++)
{
initialId = dDt.Rows[i]["ID"];
Response.Write(dDt.Rows[i]["ID"]);
}
}
while(dDt.Rows.Count > 0)
You can try this solution, in first you can get all distinct Refrence_ID and based on that you can loop to get IDs
var gCon = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;
using (var nCon = new SqlConnection(gCon))
{
try
{
nCon.Open();
String cmd = "SELECT DISTINCT Refrence_ID FROM TableA";
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(cmd, nCon);
DataTable Dt = new DataTable();
adapter.Fill(Dt);
for (int count = 0; count < Dt.Rows.Count(); count++)
{
string dCmd = "SELECT ID FROM TableA WHERE Reference_ID = '" + dt.Rows[count]["Refrence_ID"] + "'";
SqlDataAdapter dSda = new SqlDataAdapter();
dSda.SelectCommand = new SqlCommand(dCmd, nCon);
DataTable dDt = new DataTable();
dSda.Fill(dDt);
for (int i = 0; i < dDt.Rows.Count; i++)
{
Response.Write(dDt.Rows[i]["Distributor_ID"]);
}
}
}
catch (Exception e)
{
Response.Write(e.ToString());
}
finally { nCon.Close(); }
}
Thanks to all of you my friends for the effort to help me but unfortunately that didn't solved the main issue.
After lot's of research for the same i got my answer at "Recursive command", so finally my code is below
string value = "2723022"; // <== any reference id from Reference_id column
String gCmd = "SELECT DISTINCT Reference_id FROM myTable WHERE User_id >'" + value + "'";
SqlDataAdapter Sda = new SqlDataAdapter();
Sda.SelectCommand = new SqlCommand(gCmd, nCon);
DataTable Dt = new DataTable();
Sda.Fill(Dt);
for (int count = 0; count < Dt.Rows.Count; count++)
{
string dCmd = "SELECT User_id FROM dEmo_aCcounts WHERE Reference_id = '" + Dt.Rows[count]["Reference_id"] + "'";
SqlDataAdapter dSda = new SqlDataAdapter();
dSda.SelectCommand = new SqlCommand(dCmd, nCon);
DataTable dDt = new DataTable();
dSda.Fill(dDt);
for (int i = 0; i < dDt.Rows.Count; i++)
{
Response.Write(dDt.Rows[i]["User_id"]);
}
}

C# query and string coding error

I tried to get 4 names from first table and check how frequent 4 of the names appeared in each of another 20 groups and then update it on groupevenfrequency. However, I have encountered error on this coding. Appreciate if someone can assist. Thanks.
From this coding, why str[1] and str[2] and str[3] and str[4] is same teachername? But the sql command SELECT DISTINCT is already resulted 4 different teachers. Please advice.
dbConnect = new SQLiteConnection("Data Source=school.db;Version=3;");
dbConnect.Open();
cmd = new SQLiteCommand();
cmd = dbConnect.CreateCommand();
cmd.CommandText = "SELECT DISTINCT Teacher_Name from " + myTeacher + " Order by Sum_Weekly_Credit desc LIMIT 4";
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
string[] str = new string[5];
for (int i = 1; i <= 4; i++)
{
foreach (DataRow dr in dt.Rows)
{
str[i] = dr["Teacher_Name"].ToString();
cmd.ExecuteNonQuery();
}
}
dbConnect.Close();
dbConnect = new SQLiteConnection("Data Source=school.db;Version=3;");
dbConnect.Open();
cmd2 = new SQLiteCommand();
cmd2 = dbConnect.CreateCommand();
cmd3 = new SQLiteCommand();
cmd3 = dbConnect.CreateCommand();
for (int j = 1; j <= 20; j++)
{
cmd2.CommandText = "SELECT Subject FROM Group_Even_" + j + " WHERE Teacher_Name = #Teacher_Name1 OR Teacher_Name = #Teacher_Name2 OR Teacher_Name = #Teacher_Name3 OR Teacher_Name = #Teacher_Name4";
cmd2.Parameters.AddWithValue("#Teacher_Name1", str[1]);
cmd2.Parameters.AddWithValue("#Teacher_Name2", str[2]);
cmd2.Parameters.AddWithValue("#Teacher_Name3", str[3]);
cmd2.Parameters.AddWithValue("#Teacher_Name4", str[4]);
DataTable dt2 = new DataTable();
SQLiteDataAdapter da2 = new SQLiteDataAdapter(cmd2);
da2.Fill(dt2);
if (dt2.Rows.Count > 0)
{
int TempCountFrequency = dt2.Rows.Count;
cmd2.CommandText = "UPDATE GroupEvenFrequency SET GroupEven_Frequency = #GroupEven_Frequency WHERE GroupEven_Name = Group_Even_" + j + "";
cmd2.Parameters.AddWithValue("#GroupEven_Frequency", TempCountFrequency);
cmd2.ExecuteNonQuery();
}
else
{
continue;
}
}
The code you have here looks wrong....
for (int i = 1; i <= 4; i++)
{
foreach (DataRow dr in dt.Rows)
{
str[i] = dr["Teacher_Name"].ToString();
cmd.ExecuteNonQuery();
}
}
Surely you are expecting the dt.Rows to contain the 4 names you are interested in? So why have the outer loop.
So shouldn't it be more like...
string[] str = new string[5];
int i = 1;
foreach (DataRow dr in dt.Rows)
{
str[i] = dr["Teacher_Name"].ToString();
i++;
}
But as others have pointed out your overall approach could do with a rethink. The code won't cater for the fact that you might not have 4 distinct teacher names

Not getting data in predefined Datagrid columns

I have a predefined datagrid columns which loads on form loading.What I wanted was when I enter id or name of product in the text box I wanted it to display in the datagrid columns.But when I enter Id or product name nothing gets displayed in the columns.I've tried the followong code:
public Form1()
{
InitializeComponent();
load();
}
void load()
{
string cc = "";
int n;
if (int.TryParse(textBox1.Text, out n))
{
cc = "product_Id = " + textBox1.Text.Trim();
}
else
{
cc = "product_Name LIKE '%" + textBox1.Text.Trim() + "%'";
}
if (string.IsNullOrEmpty(textBox1.Text))
{
cc = "1 = 1";
}
SqlConnection con = new SqlConnection("Data Source=SUMIT;Initial Catalog=Project;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select product_Name as [Product Name],cast(actual_Sp as INT) * '" + textBox2.Text + " 'as [Actual SP] from Product WHERE " + cc, con); ;
cmd.CommandType = CommandType.Text;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = null;
dataGridView1.ColumnCount = 7;
dataGridView1.Columns[0].Name = "ProductId";
dataGridView1.Columns[0].HeaderText = "PID";
dataGridView1.Columns[0].DataPropertyName = "product_Id";
dataGridView1.Columns[1].HeaderText = "S.N.";
dataGridView1.Columns[1].Name = "Serial Number";
// dataGridView1.Columns[1].DataPropertyName = "ContactName";
dataGridView1.Columns[2].Name = "Particulars";
dataGridView1.Columns[2].HeaderText = "Particulars";
dataGridView1.Columns[2].DataPropertyName = "product_Name";
dataGridView1.Columns[3].Name = "Unit Quantity";
dataGridView1.Columns[3].HeaderText = "Unit Quantity";
//dataGridView1.Columns[3].DataPropertyName = "product_Name";
dataGridView1.Columns[4].Name = "Amount";
dataGridView1.Columns[4].HeaderText = "Amount";
// dataGridView1.Columns[4].DataPropertyName = "product_Name";
dataGridView1.Columns[5].Name = "Discount";
dataGridView1.Columns[5].HeaderText = "Discount";
//dataGridView1.Columns[5].DataPropertyName = "product_Name";
dataGridView1.Columns[6].Name = "Sub-Total";
dataGridView1.Columns[6].HeaderText = "Sub-Total";
// dataGridView1.Columns[6].DataPropertyName = "product_Name";
dataGridView1.DataSource = dt;
}
Your SQL query returns a table with columns Product Name and Actual SP but in your datagridview you are assigning ;
dataGridView1.Columns[0].DataPropertyName = "product_Id";
but product_Id column is not in your data table.
Change as follows;
dataGridView1.Columns[0].DataPropertyName = "Actual SP";
dataGridView1.Columns[2].DataPropertyName = "Product Name";
Then it should work.
You must add each column to the DataGridView like:
dataGridView1.Columns.Add("ProductId","PID");
dataGridView1.Columns["ProductId"].DataPropertyName="product_Id";

Categories