Q:
I want to rename my data table column names .
I tried this :
dt.Columns[8].ColumnName = "regnum";
dt.AcceptChanges();
but my data is lost after that !!
dt.Columns[8].ColumnName = "regnum";
This just binds your Columns[8] to the non-existing "regnum" column in the Db.
If you want to rename the actuals Db column, execute an SQL script.
But my guess is you actually want to change the Caption:
dt.Columns[8].Caption = "regnum";
Following is the example:
DataTable Dt = new DataTable();
DataColumn Dc = new DataColumn("Name");
DataColumn Dc1 = new DataColumn("ID");
Dt.Columns.Add(Dc);
Dt.Columns.Add(Dc1);
DataRow dr = Dt.NewRow();
dr["name"] = "1";
dr["ID"] = "111";
Dt.Rows.Add(dr);
dr = Dt.NewRow();
dr["name"] = "2";
dr["ID"] = "11112";
Dt.Rows.Add(dr);
Dt.Columns[0].ColumnName = "ddsxsd";
Dt.AcceptChanges();
I did not find any data loss!!!!!!!! Because it will merely change the column name.
EDIT
You can also bring your desired column names from your Stored Procedures.
Try this:
dataTable.Columns["ExistingColumnName"].ColumnName = "regnum";
Also may this code serve someone!
I have a realize that this is the easiest way just like #Henk said:
using (SqlDataAdapter da = new SqlDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
da.SelectCommand = cmd;
da.Fill(dt);
dt.Columns[0].ColumnName = "Item NO";
dt.Columns[1].ColumnName = "LocalCode";
dt.Columns[2].ColumnName = "Currency";
dt.Columns[3].ColumnName = "Menu Flag";
dt.Columns[4].ColumnName = "Item Class";
dt.Columns[4].ColumnName = "Dress Sort";
return dt;
}
Related
I am selecting data from SQL into datagrid, the code works fine, but it is deleting the previous data from my datagrid.
My code (C# WPF SQL datagrid):
private void enter(object sender, KeyEventArgs e)
{
try
{
if (e.Key == Key.Enter)
{
SqlConnection com = new SqlConnection("Server = localhost; database = PrimaSOFT ; integrated security = true");
SqlCommand cmd = new SqlCommand("produktit", com);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Barkodi", txtBarkodi.Text);
//Created a new DataTable
SqlDataAdapter da = new SqlDataAdapter(cmd);
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 = "Barkodi";//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.String");
dc2.ColumnName = "Emertimi";
DataColumn dc3 = new DataColumn();
dc3.DataType = System.Type.GetType("System.Decimal");
dc3.ColumnName = "Sasia";
DataColumn dc4 = new DataColumn();
dc4.DataType = System.Type.GetType("System.Decimal");
dc4.ColumnName = "Cmimi";
DataColumn dc5 = new DataColumn();
dc5.DataType = System.Type.GetType("System.String");
dc5.Caption = "sds";
dc5.ColumnName = "TVSH";
DataColumn dc6 = new DataColumn();
dc6.DataType = System.Type.GetType("System.String");
dc6.ColumnName = "Total";
dc6.Expression = "Cmimi * Sasia";//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);
dataTable.Columns.Add(dc5);
dataTable.Columns.Add(dc6);
dtgartikujt.ItemsSource = dataTable.DefaultView;//Set the DataGrid ItemSource to this new generated DataTable
com.Open();//Open the SQL connection
SqlDataReader reader = cmd.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];
dr[3] = reader[3];
dr[4] = reader[4];
dataTable.Rows.Add(dr);//Add the new created DataRow to the DataTable
}
}
}
Sum code
object sumObject;
sumObject = dataTable.Compute("Sum(Totali)",
string.Empty);
txttotali.Text = sumObject.ToString();
I am expecting a new data to be showed in datagrid without deleting previous data.
How should I approach this?
Edited: I also attached the sum code, to sum the datagrid column, and display to textbox
As I think I understand what you are doing : separate dataTable code from Sql(ADO.NET) code and run dataTable part once only. So for run CreateTable in form_load for example :
public void CreateTable()
{
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 = "Barkodi";//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.String");
dc2.ColumnName = "Emertimi";
DataColumn dc3 = new DataColumn();
dc3.DataType = System.Type.GetType("System.Decimal");
dc3.ColumnName = "Sasia";
DataColumn dc4 = new DataColumn();
dc4.DataType = System.Type.GetType("System.Decimal");
dc4.ColumnName = "Cmimi";
DataColumn dc5 = new DataColumn();
dc5.DataType = System.Type.GetType("System.String");
dc5.Caption = "sds";
dc5.ColumnName = "TVSH";
DataColumn dc6 = new DataColumn();
dc6.DataType = System.Type.GetType("System.String");
dc6.ColumnName = "Total";
dc6.Expression = "Cmimi * Sasia";//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);
dataTable.Columns.Add(dc5);
dataTable.Columns.Add(dc6);
dtgartikujt.ItemsSource = dataTable.DefaultView;//Set the DataGrid ItemSource to this new generated DataTable
}
And the rest of code :
long sum=0;
private void enter(object sender, KeyEventArgs e)
{
try
{
if (e.Key == Key.Enter)
{
SqlConnection com = new SqlConnection("Server = localhost; database = PrimaSOFT ; integrated security = true");
SqlCommand cmd = new SqlCommand("produktit", com);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Barkodi", txtBarkodi.Text);
//Created a new DataTable
SqlDataAdapter da = new SqlDataAdapter(cmd);
com.Open();//Open the SQL connection
SqlDataReader reader = cmd.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];
dr[3] = reader[3];
dr[4] = reader[4];
// sum+= Convert.ToInt64(reader[4]); // use the total index instead of 4 . or use reader["total"];
dataTable.Rows.Add(dr);//Add the new created DataRow to the DataTable
// or maybe dtgartikujt.Rows.Add(dr);
}
// textbox1.Text=sum.Tostring();
}
}
I am working with a small application where the user can retrieve specific data from SQL populate the datagrid with the data. The user can retrieve data from SQL Database where he write a barcode in textbox then the data he searched for will appear.
Until now i used this code
try
{
if (e.Key == Key.Enter)
{
SqlConnection con = new SqlConnection("Server = localhost;Database = Bilanc; Integrated Security = true");
SqlCommand cmd = new SqlCommand("product", con); // Using a Store Procedure.
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable("dtList");
cmd.Parameters.AddWithValue("#Barcod", txtcode.Text);
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 = "#Barcod";//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.String");
dc2.ColumnName = "#Product";
DataColumn dc3 = new DataColumn();
dc3.DataType = System.Type.GetType("System.Decimal");
dc3.ColumnName = "#QTY";
DataColumn dc4 = new DataColumn();
dc4.DataType = System.Type.GetType("System.Decimal");
dc4.ColumnName = "#Price";
DataColumn dc5 = new DataColumn();
dc5.DataType = System.Type.GetType("System.String");
dc5.ColumnName = "#Tax";
DataColumn dc6 = new DataColumn();
dc6.DataType = System.Type.GetType("System.String");
dc6.ColumnName = "Total";
dc6.Expression = "#Price * #QTY";//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);
dataTable.Columns.Add(dc5);
dataTable.Columns.Add(dc6);
dtg.ItemsSource = dataTable.DefaultView;//Set the DataGrid ItemSource to this new generated DataTable
con.Open();//Open the SQL connection
SqlDataReader reader = cmd.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];
dr[3] = reader[3];
dr[4] = reader[4];
dataTable.Rows.Add(dr);//Add the new created DataRow to the DataTable
}
}
}
catch (Exception)
{
MessageBox.Show("The product you are searching doesn't exist ");
}
}
The code works fine, but when i got stuck is when i retrieve data from SQL the new data overwrite the previous data.
My question how i can keep the previous data
Thanks to everyone
I am trying to build datagridview that consist from two part
one part came from database and the other part is collected information about files on local hard disk and show it as one part but I am getting error message that says
Rows cannot be programmatically added to the datagridview rows
collection when the control is data-bound
Note:
knowing That data within datagridview will be used later to modifies data on oracle database
I had upload imag for more understanding the first two column are from database
private void ListFileToBePatched()
{
try
{
string connstr = "data source=orcl;user id=user;password=pwd";
string cmdstr = #"SELECT OFFICE_CODE as ""Office Code"",
IP_ADDRESS as ""Office IP""
FROM table";
string[] array = Directory.GetFiles(SBankfilespath, "*.txt");
using (OracleConnection conn = new OracleConnection(connstr))
using (OracleCommand cmd = new OracleCommand(cmdstr, conn))
{
conn.Open();
OracleTransaction trans = conn.BeginTransaction();
OracleDataReader OraReader = cmd.ExecuteReader();
DataTable dt = new DataTable();
DataColumn OfficeCodecolumn = new DataColumn();
OfficeCodecolumn.DataType = System.Type.GetType("System.String");
OfficeCodecolumn.ColumnName = "Office Code";
dt.Columns.Add(OfficeCodecolumn);
DataColumn OfficeIPcolumn = new DataColumn();
OfficeIPcolumn.DataType = System.Type.GetType("System.String");
OfficeIPcolumn.ColumnName = "Office IP Address";
dt.Columns.Add(OfficeIPcolumn);
DataColumn FileNamecolumn = new DataColumn();
FileNamecolumn.DataType = System.Type.GetType("System.String");
FileNamecolumn.ColumnName = "File Name";
dt.Columns.Add(FileNamecolumn);
DataColumn FullFilePathcolumn = new DataColumn();
FullFilePathcolumn.DataType = System.Type.GetType("System.String");
FullFilePathcolumn.ColumnName = "Full File Path";
dt.Columns.Add(FullFilePathcolumn);
DataColumn DateCreatedcolumn = new DataColumn();
DateCreatedcolumn.DataType = System.Type.GetType("System.String");
DateCreatedcolumn.ColumnName = "Date Created";
dt.Columns.Add(DateCreatedcolumn);
DataColumn Datemodifiedcolumn = new DataColumn();
Datemodifiedcolumn.DataType = System.Type.GetType("System.String");
Datemodifiedcolumn.ColumnName = "Date modified";
dt.Columns.Add(Datemodifiedcolumn);
foreach (string FullFilePath in array)
{
DataRow row = dt.NewRow();
row[2] = Path.GetFileName(FullFilePath);
row[3] = FullFilePath;
row[4] = File.GetCreationTime(FullFilePath);
row[5] = File.GetLastWriteTime(FullFilePath);
dt.Rows.Add(row);
}
dt.Load(OraReader);
DataView view = new DataView(dt);
DGV_PatchStatus.DataSource = view;
}
FileCount.Text = "File Count ( " + DGV_PatchStatus.Rows.Count.ToString() + " )";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You could use the DataTable.NewRow method to add the row to your DataTable.
foreach (string FullFilePath in array)
{
DataRow r = DT.NewRow();
r[0] = Path.GetFileName(FullFilePath);
r[1] = FullFilePath;
r[2] = File.GetCreationTime(FullFilePath);
r[3] = File.GetLastWriteTime(FullFilePath);
}
Then simply bind the DT again as DataSource
DGV_PatchStatus.DataSource = DT;
EDIT:
what I really need is that for each office has list of files
If you have several files for each office-row you should have a look on this Tree-View-Tutorial this might really be helpful to achieve your desired results.
Here is also a Nested-DataGrid-Example that might also be of help. Good luck.
Make Class For your data after reading from db assign data to that object and put object into List afterwards initialize DGV_PatchStatus.DataSource to that list, when you need to add new row simply add data object to that list and re initialize DGV_PatchStatus DataSource
I am generating a DataTable in C# and I need to disable sorting the columns via code. The code is something like:
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("File_Name");
dt.Columns.Add("Create_Date");
dt.Columns.Add("Status");
dr = dt.NewRow();
dataGridView1.DataSource = dt;
How can this be accomplished? I did check for things like dt.SortMode = <something disabled> but so far didn't find any SortOrder on the data element.
Here's a more robust example. I tested this in Windows forms application (.NET 4.5, VS 2012)
DataTable dt = new DataTable();
dt.Columns.Add("File_Name");
dt.Columns.Add("Create_Date");
dt.Columns.Add("Status");
DataRow dr = dt.NewRow();
dr["File_Name"] = "abc.txt";
dr["Create_Date"] = DateTime.Now;
dr["Status"] = "Pending";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["File_Name"] = "xyz.bmp";
dr["Create_Date"] = DateTime.Now;
dr["Status"] = "Complete";
dt.Rows.Add(dr);
dataGridView1.DataSource = dt;
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
col.SortMode = DataGridViewColumnSortMode.NotSortable;
}
Hope this helps.
:) David
"AllowUserToOrderColumns" has nothing to do with sorting data, it determines whether or not the user is allowed to rearrange the columns in the grid. You can disable sorting certain grid columns by setting the respective columns' SortMode as such
myDataGridViewTextBoxColumn.SortMode = DataGridViewColumnSortMode.NotSortable
When am trying to fill Combobox
con.Open();
da = new SqlDataAdapter("Mt_Post_select",con);
//Mt_Post is Stored procedure with Select Command
ds1 = new DataSet();
da.Fill(ds1, "Mt_Post");
// The table has only one row
comboBox1.DataSource = ds1.Tables[0];
comboBox1.DisplayMember = "Mt_Post";
It bind But shows instead of data it having System.Data.DataRowView
What is the wrong this code Please anyone tell me
Replace Mt_Post in comboBox1.DisplayMember = "Mt_Post"; with the name of column whose value you would like to display.
I hope the following sample helps;
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Email");
dt.AcceptChanges();
DataRow dr0 = dt.NewRow();
dr0[0] = "Kadir Sumerkent";
dr0[1] = "kadir#sumerkent.com";
DataRow dr1 = dt.NewRow();
dr1[0] = "Kadir Sumerkent 2";
dr1[1] = "kadir#sumerkent2.com";
dt.Rows.Add(dr0);
dt.Rows.Add(dr1);
dt.AcceptChanges();
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Email";
comboBox1.DataSource = dt;
Let's try this:
Suppose your Stored Procedure is like the code below:
SELECT
Users.User_name AS username
Users.User_Code AS userID
FROM Users
-- WHERE CONDITONS ARE APPLIED
Now in order to Fetch this DataSet you are going to do as follows:
// YOUR OWN CODE
con.Open();
da = new SqlDataAdapter("Mt_Post_select",con);
//Mt_Post is Stored procedure with Select Command
ds1 = new DataSet();
// JUST FILL THE DataSet in THIS WAY
da.Fill(ds1);
// JUST TO MAKE SURE WE HAVE AN EMPTY COMBOBOX
comboBox1.Items.Clear();
comboBox1.DataSource = null;
// NOW POPULATE comboBox1 LIKE THIS
if (ds.Tables[0].Rows.Count > 0)
{
comboBox1.DataSource = ds1.Tables[0];
comboBox1.DisplayMember = "username";
comboBox1.ValueMember = "userID"
}