how to bind a datagrid? - c#

i tried to bind a datagrid but there is a problem in binding of my datagrid..
C# code
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("Source");
dt.Columns.Add("ID", Type.GetType("System.String"));
dt.Columns.Add("Desc", Type.GetType("System.String"));
Insurance oInsurance = new Insurance();
List<Value> lstValue = oInsurance.Category.ValueList;
foreach (Value item in lstValue)
{
DataRow dr = dt.NewRow();
dr[0] = item.Key.ToString();
dr[1] = item.Value.ToString();
dt.Rows.Add(dr);
}
grdCategory.DataSource = ds;
grdCategory.DataMember = "Source";
grdCategory.DataTextField = "Desc";
grdCategory.DataValueField = "ID";
grdCategory.DataBind();
Thanks

well... try to post the error that you are getting from this...
but... if you don't need the DataSet you could just do like this...
Insurance oInsurance = new Insurance();
List<Value> lstValue = oInsurance.Category.ValueList;
grdCategory.DataSource = lstValue;
grdCategory.AutoGenerateColumns = true; //not sure that's the property
grdCategory.DataBind();

Related

How to add a new data to a datagrid keeping the previously existed data there too?

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();
}
}

Simple DataTable, BindingSource, DataGrid view shows no data

I have this super simple example, where I placed a DataGridView on a form, then with the follow code:
public Form1()
{
InitializeComponent();
var dt = new DataTable();
var col = dt.Columns.Add("Column 1");
var row = dt.NewRow();
row[0] = "test";
var bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
}
no rows in the Grid. I must be missing something simple.
Try to add a newly created row to the DataTable.Rows collection:
var dt = new DataTable();
var col = dt.Columns.Add("Column 1");
var row = dt.NewRow();
row[0] = "test";
dt.Rows.Add(row);

GridView doesn't show my datasource

I have gridview "gvData" ,i need to fetch the data of my function to gridview :
(I am using c# application)
algorithm.prison obj=new prison();
gvData.DataSource= obj.TitForTat();
After run i have a empty gridview.
Here is my code:
public DataSet TitForTat()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("myt");
dt.Columns.Add(new DataColumn("iteration", typeof(int)));
dt.Columns.Add(new DataColumn("prison1", typeof(string)));
dt.Columns.Add(new DataColumn("prison2", typeof (string)));
prison[] prisons = new prison[2];
prisons[0] = new prison();
prisons[1] = new prison();
//---------------------------
DataRow dr = dt.NewRow();
prisons[0]._state = "c";
prisons[1]._state = valueOfState[rd.Next(0, 1)];
dr["iteration"] = 0;
dr["prison1"] = "c";
dr["prison2"] = prisons[1]._state;
dt.Rows.Add(dr);
//----------------------
for (int i = 1; i <= _iteration; i++)
{
prisons[0]._state = prisons[1]._state;
prisons[1]._state = valueOfState[rd.Next(0, 1)];
DataRow dr1 = dt.NewRow();
dr1["iteration"] =i;
dr1["prison1"] = prisons[0]._state;
dr1["prison2"] = prisons[1]._state;
dt.Rows.Add(dr1);
}
ds.Tables.Add(dt);
return ds;
}
If it's an ASP.NET-webforms GridView-control you need to call DataBind() after you have assigned the DataSource:
gvData.DataSource = obj.TitForTat();
gvData.DataBind();
If it's winforms you have to set the DataMember property if you use a DataSet instead of a DataTable:
gvData.DataSource = obj.TitForTat();
gvData.DataMember = "myt";
... or use a DataTable in the first place:
DataSet ds = obj.TitForTat();
if(ds.Tables.Count > 0)
gvData.DataSource = ds.Tables[0];

Sort DataGridView according particular column before add

I have DataGridView that i am adding items via DataTable
This items read from XML file and inside this XML file,
those items not sorted and i want to sort is before add to my DataGridView
private void UpdateDataGdirView(List<Vendor> list)
{
DataTable dt = new DataTable();
dt.Columns.Add("Column1", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Column2", typeof(string));
dt.Columns.Add("Column3", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Column4", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Column5", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Column6", System.Type.GetType("System.Boolean"));
DataRow dr;
foreach (Vendor vendor in list)
{
dr = dt.NewRow();
dr["Column1"] = vendor.IsVendorChecked;
dr["Column2"] = vendor.Number;
dr["Column3"] = vendor.Name;
dr["Column4"] = vendor.Size;
dr["Column5"] = vendor.Path;
dr["Column6"] = vendor.Path2;
dt.Rows.Add(dr);
}
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
this.Invoke((MethodInvoker)delegate { dataGridView1.DataSource = dt; });
}
you can use
dt.defaultview.sort="columnname asc/desc"
and then bind the datatable to its destination.
I think you should use DataView for this. Like :
DataTable orders = dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection<DataRow> query =
from order in orders.AsEnumerable()
orderby order.Field<decimal>("TotalDue")
select order;
DataView view = query.AsDataView();
bindingSource1.DataSource = view;
Follow this link : Query on DataView
OR
You can use like :
DataTable orders = dataSet.Tables["SalesOrderHeader"];
DataView dv = new DataView(orders);
dv.Sort = "TotalDue";
dataGridView1.DataSource = dv;

How to rename the datatable column name without losing the data?

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;
}

Categories