Customizing a datagridview runtime - c#

I am new to C#,ASP.NET.
I am creating a small application where I want to list some data.
Below mentioned function binds data with 3 columns.
Property Name, Property 'ReferenceID' and Post Date.
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("PROC_RECENT_HISTORY_HEADER"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", Member);
cmd.Connection = con;
con.Open();
reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
con.Close();
}
Asp.net
<asp:GridView ID="GridView1" runat="server" class="form-control" Width="100%" ViewStateMode="Enabled" AutoGenerateColumns = "false">
<Columns>
<asp:BoundField DataField="PRP_NAME" HeaderText="Property Name"/>
<asp:BoundField DataField="PRP_REF_NO" HeaderText="Reference"/>
<asp:BoundField DataField="PRP_CRDT" HeaderText="Post Date"/>
</Columns>
</asp:GridView>
I want to display two extra columns along with this data.
One is for 'No.' as a serial number for each rows and another one column is 'Action', its like a hyperlink, when I click here page must be redirected to an action based on 'property_ReferenceID' of corresponding row.
how to add columns run time ?

Here GridView1.DataSource = reader; if it consists of 3 columns then it will bind with 3 columns data.
step1: create the columns manually by adding columns
step2: store the data into datatable
DataTable datatable = new DataTable();
datatable.Load(cmd.ExecuteReader());
step3 : the loop through each object from the datatable
DataTable dt= new DataTable();
DataColumn dc1 = new DataColumn("PropertyName");
DataColumn dc2 = new DataColumn("PropertyID");
DataColumn dc3 = new DataColumn("Postdate");
DataColumn dc4 = new DataColumn("columnName4");
DataColumn dc5 = new DataColumn("columnName5");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
dt.Columns.Add(dc5);
foreach (DataRow row in datatable.Rows)
{
DataRow dr = dt.NewRow();
dr[0] = row[propertyname];
dr[1] = row[Propertytype];
dr[2] = row[postdate];
dr[3] = "YES";
dr[4] = "NO";
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;

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

c# datagrid sql population

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

asp.net grid view data binding without database

I am a beginner in asp.net and c#. I want to bind image and name to gridview without any database by hardcoding them in code behind.
I tried like below but these values are not binded to Gridview1. Can anyone tell me where it goes wrong?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="Profile_Name" HeaderText="Profile_Name" />
<asp:BoundField DataField="ImageUrl" HeaderText="ImageUrl" />
</Columns>
protected GridView GridView1;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.loadTable();
}
}
private void loadTable()
{
DataSet ds = new DataSet();
DataTable dt;
DataRow dr;
DataColumn pName;
DataColumn pImage;
dt = new DataTable();
pName = new DataColumn("Profile_Name", Type.GetType("System.String"));
pImage= new DataColumn("ImageURL", Type.GetType("System.String"));
dt.Columns.Add(pName);
dt.Columns.Add(pImage);
dr = dt.NewRow();
dr["Profile_Name"] = "John Cena";
dr["ImageUrl"] = "C:\\Users\\Desktop\\src\\Project\\Project.Web.WebForms\\Content\\Images\\Friends-PNG-Photos.png";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Profile_Name"] = "Hannah Ray";
dr["ImageUrl"] = "C:\\Users\\Desktop\\src\\Project\\Project.Web.WebForms\\Content\\Images\\Image.png";
dt.Rows.Add(dr);
ds.Tables.Add(dt);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
In the background you can make a new DataTable:
DataTable dt = new DataTable();
Then you can add data columns and rows through the dt.Rows and dt.Columns methods, and then set:
DataGridView.ItemsSource = dt.defaultview;
Hope that you find this helpful.
You can bind all objects to a DataGrid:
datagrid.DataSource = object;
datagrid.DataBind();

how to assign values to DataKeyNames in gridview programatically using C#

I have a GridView. I am adding columns in it through c# in GridView gvExemptSub and retrieving data from another GridView gvSubj on button click. I want to assign data row values to DataKeyNames which I am retrieving from another GridView but I don't know how.
<asp:GridView ID="gvExemptSub" runat="server" Width="100%" DataKeyNames="LID,BID">
<Columns>
</Columns>
</asp:GridView>
protected void BtnAddSubj_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.TableName = "ExemptSubj";
dt.Columns.Add("QUALIFICATION", typeof(string));
dt.Columns.Add("SUBJECT", typeof(string));
dt.Columns.Add("LEVEL", typeof(string));
dt.Columns.Add("UNIVERSITY", typeof(string));
DataRow dr;
foreach (GridViewRow srow in gvSubj.Rows)
{
if (srow.RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr[0] = ddlQualification.SelectedItem;
string SUBJECT = srow.Cells[1].Text;
SUBJECT = SUBJECT.Replace("amp;", "");
dr[1] = SUBJECT;
dr[4] = int.Parse(gvSubj.DataKeys[srow.RowIndex]["LEVEL_ID"].ToString());
dr[2] = srow.Cells[2].Text;
dr[3] = ddlUNI.SelectedItem.Text;
dr[5] = ddlUNI.SelectedValue;
dt.Rows.Add(dr);
}
}
ViewState["ExemptSubj"] = dt;
//gvExemptSubj.DataKeyNames = (dr[4], dr[5])
gvExemptSubj.DataSource = dt;
gvExemptSubj.DataBind();
}
You can bind them programmatically with an string array:
GridView1.DataKeyNames = new string[2] { "ColumnA", "ColumnB" };

Dynamic databinding to gridview

I've a grid view and I want to bind some data to this Gridview at runtime.
In my button click event I wrote like this
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataRow dr;
DataColumn dc = new DataColumn();
dc.Caption = "Name";
dc.DataType = Type.GetType("System.String");
dc.ColumnName = "Name";
dt.Columns.Add(dc);
dr = dt.NewRow();
dr["Name"] = TextBox1.Text;
dt.Rows.Add(dr);
ds.Tables.Add(dt);
GridView1.DataSource = ds;
GridView1.DataBind();
}
It is working fine and displays data. But now I want to add multiple rows to gridview. When I try to bind it only one row adding to grid view every time. (i.e recent value entered in text box). I want to append rows to gridview.
How can I do this?
Store ds to a viewstate.
Then when you r adding a new row. Retrieve the dataset from viewstate and add a new row containing recent value entered in text box.
as :
if(ViewState["ds"]!=null)
{
DataSet ds=(DataSet) ViewState["ds"];
dr = ds.Tables[0].NewRow();
dr["Name"] = TextBox1.Text;
ds.Tables[0].Rows.Add(dr);
GridView1.DataSource = ds;
GridView1.DataBind();
}

Categories