Dynamic databinding to gridview - c#

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

Related

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

Add row datagridview at every button click

I have on a usercontrol a datagridview. I created a datatable and I set the source of datagrid to be this datatable. I want,at runtime,to be able to add how many rows on gridview I want at every button click.
My code :
private DataTable CreateTable()
{
Datatable table=new Datatable();
table.Columns.Add("Name".ToString());
table.Columns.Add("Size".ToString());
DataRow dr = table.NewRow();
dr["Name"] = "Mike";
DataRow dr2 = table.NewRow();
dr2["Name"] = "Ryan;
DataRow dr3 = table.NewRow();
dr3["Name"] = "Taylor";
dr["Size"] = " one";
dr2["Size"] = "two";
table.Rows.Add(dr);
table.Rows.Add(dr2);
table.Rows.Add(dr3);
return table;
//and on my constructor I set gridview.DataSource=Datatable;
}
//Code on the event:
private void button_Click(object sender, EventArgs e)
{
DataRow NewRow = table.NewRow();
table.Rows.Add(NewRow);
}
You need to define the DataTable at form level. Then in button click you can do:
private void button_Click(object sender, EventArgs e)
{
DataRow NewRow = table.NewRow();
table.Rows.Add(NewRow);
gridview.DataSource=table; //specify the source
}
For defining table at form level:
DataTable table; //DataTable at form level
private DataTable CreateTable()
{
table=new Datatable(); //here insntianting the form level table.
table.Columns.Add("Name".ToString());
table.Columns.Add("Size".ToString());
DataRow dr = table.NewRow();
dr["Name"] = "Mike";
DataRow dr2 = table.NewRow();
dr2["Name"] = "Ryan;
DataRow dr3 = table.NewRow();
dr3["Name"] = "Taylor";
dr["Size"] = " one";
dr2["Size"] = "two";
table.Rows.Add(dr);
table.Rows.Add(dr2);
table.Rows.Add(dr3);
return table;
//and on my constructor I set gridview.DataSource=Datatable;
}
I would recommend the following approach for better handling.
Create generic list, for every click append the list with the new set of data, then convert the list to DataTable as said in the below link, then bind DataTable to the grid.
Convert generic List/Enumerable to DataTable?
If you want sample code please let me know.

How to extract data from a TextBox to a GridView (multiple rows to be displayed in the GridView)?

I have used the following code to display data from a TextBox to a GridView without saving the data to the database(Two TextBoxes and a Button). When I enter the Name and City in the TextBoxes, and click on the Button, those values will be displayed in the Gridview. It is working as expected without any errors. But I want to tweak the code a bit so that the GridView should be able to add new data from the Textbox by retaining the old data as it is in the Gridview (multiple rows should be displayed in the Gridview instead of single rows).
It is a web-based ASP.NET application using C# coding (Visual Studio 2010).
Can you make the necessary changes to the code given below so as to implement the above functionality?
public partial class _Default : System.Web.UI.Page
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnTextDisplay_Click(object sender, EventArgs e)
{
DataColumn dc1 = new DataColumn("Name");
DataColumn dc2 = new DataColumn("City");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
DataRow dr = dt.NewRow();
dr[0] = txtName.Text;
dr[1] = txtCity.Text;
dt.Rows.Add(dr);
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
}
}
You have to persists your data between postbacks, you have many options here: by Session, ViewState, Cache and some other.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostback)
{
dt = Session["data_table"] as DataTable;
}
}
protected void btnTextDisplay_Click(object sender, EventArgs e)
{
if (dt == null)
{
dt = new DataTable();
DataColumn dc1 = new DataColumn("Name");
DataColumn dc2 = new DataColumn("City");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
}
DataRow dr = dt.NewRow();
dr[0] = txtName.Text;
dr[1] = txtCity.Text;
dt.Rows.Add(dr);
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
Session["data_table"] = dt;
}

How to display values entered via a TextBox in a GridView on button-click without saving the data to the database?

I have created two TextBoxes to enter the FirstName and LastName of an employee and a button in a web-based ASP.NET application using C# on Visual studio 2010.when I click on the button , the values that I enter in the TextBoxes should be displayed in a Gridview without being stored in the database.
How can I do that? Can you provide a sample code to execute the above mentioned functionality?
This is a working code..
protected void Page_Load(object sender, EventArgs e)
{
dt = new DataTable();
DataColumn dc1 = new DataColumn("FIRST NAME");
DataColumn dc2 = new DataColumn("LAST NAME");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
DataRow dr1 = dt.NewRow();
GridView1.DataSource = dt;
GridView1.DataBind();
}
DataTable dt;
protected void Button1_Click(object sender, EventArgs e)
{
DataRow dr1 = dt.NewRow();
dr1[0] = TextBox1.Text;
dr1[1] = TextBox2.Text;
dt.Rows.Add(dr1);
GridView1.DataSource = dt;
GridView1.DataBind();
}
You can access gridview in code like that:
var gridview = document.getElementById("<%=Gridview1.ClientID%>");
After you can access in that gridview will be methods to renew/add/delete information in client side. But notice, that you also have to tell your server-side that you renewed the information in DB, so he can save changes to DB.
I expect that you should send ajax request for renewing data in DB, and use the code to access grid from javascript and renew data in client-side over javascript.
Take the values which you have entered in textbox in a DataTable and the give that dataTable as a datasource to that datagrid.
Check this link
http://forums.asp.net/t/1672122.aspx/1
the code you provided works fine. but it will add only one record to GridView. If you added a new record then the old data will be replaced. So we have to preserve the old record.
Just enter the below code to the button click event.
protected void Button1_Click(object sender, EventArgs e)
{
if(Session["Data"] == null) //Checking if the session contain any value.
{
DataTable dt = new DataTable(); //creating the columns.
dt.Columns.Add("Name");
dt.Columns.Add("Price");
dt.Columns.Add("Stock");
DataRow dr = dt.NewRow(); //Create a new row and add the row values.
dr[0] = TextBox1.Text;
dr[1] = TextBox2.Text;
dr[2] = TextBox3.Text;
dt.Rows.Add(dr);
GridView1.DataSource = dt; //Populate values to Gridview.
GridView1.DataBind();
Session["Data"] = dt; //Storing that table into session.
}
else
{
DataTable dt = new DataTable();
dt = (DataTable)Session["Data"]; //Retrieve the stored table from session.
DataRow dr = dt.NewRow(); //Adding a new row to existing table.
dr[0] = TextBox1.Text;
dr[1] = TextBox2.Text;
dr[2] = TextBox3.Text;
dt.Rows.Add(dr);
GridView1.DataSource = dt; //Populate new table values to Gridview.
GridView1.DataBind();
Session.Remove("Data"); //Clear the session.
Session["Data"] = dt; //Store the new table to the session.
}
}
private int id = 0;
private void dataGridView1_CellClick(object sender,
DataGridViewCellEventArgs e)
{
int RowIndex = e.RowIndex;
id= Convert.ToInt32(dataGridView1.Rows[RowIndex].Cells[0].Value.ToString());
textBox1.Text = dataGridView1.Rows[RowIndex].Cells[1].Value.ToString();
textBox2.Text = dataGridView1.Rows[RowIndex].Cells[2].Value.ToString(); textBox3.Text = dataGridView1.Rows[RowIndex].Cells[3].Value.ToString();
textBox4.Text = dataGridView1.Rows[RowIndex].Cells[4].Value.ToString();
}

Filling of ComboBox with Dataset

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

Categories