asp.net grid view data binding without database - c#

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

Related

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

Customizing a datagridview runtime

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;

how to delete from gridview without database "check to determine if the object is null before calling the method"

The ff are codes in my .cs file
private void BindGridview(int rowcount)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("Code", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Course", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Credit", typeof(String)));
if (ViewState["CurrentData"] != null)
{
for (int i = 0; i < rowcount + 1; i++)
{
dt = (DataTable)ViewState["CurrentData"];
if (dt.Rows.Count > 0)
{
dr = dt.NewRow();
dr[0] = dt.Rows[0][0].ToString();
}
}
dr = dt.NewRow();
dr[0] = this.cboCourseCode.Text;
dr[1] = this.txtCourseName.Text;
dr[2] = this.txtCredit.Text;
dt.Rows.Add(dr);
}
else
{
dr = dt.NewRow();
dr[0] = this.cboCourseCode.Text;
dr[1] = this.txtCourseName.Text;
dr[2] = this.txtCredit.Text;
dt.Rows.Add(dr);
}
// If ViewState has a data then use the value as the DataSource
if (ViewState["CurrentData"] != null)
{
GridView1.DataSource = (DataTable)ViewState["CurrentData"];
GridView1.DataBind();
}
else
{
// Bind GridView with the initial data assocaited in the DataTable
GridView1.DataSource = dt;
GridView1.DataBind();
}
// Store the DataTable in ViewState to retain the values
ViewState["CurrentData"] = dt;
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[e.RowIndex].Delete();
ViewState["dt"] = dt;
BindGrid();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string Code = e.Row.Cells[0].Text;
foreach (Button button in e.Row.Cells[3].Controls.OfType<Button>())
{
if (button.CommandName == "Delete")
{
button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + Code + "?')){ return false; };";
}
}
}
}
protected void cboCourseCode_SelectedIndexChanged(object sender, EventArgs e)
{
this.Populate_Course_Details();
}
protected void BtnAdd_Click(object sender, EventArgs e)
{
/* DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Code"), new DataColumn("Course"), new DataColumn("Credit") });
dt.Rows.Add(this.cboCourseCode.Text, this.txtCourseName.Text, this.txtCredit.Text);
ViewState["dt"] = dt;
BindGrid();*/
if (ViewState["CurrentData"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentData"];
int count = dt.Rows.Count;
BindGridview(count);
}
else
{
BindGridview(1);
}
}
My aspx file also has this gridview
<asp:GridView ID="GridView1" CssClass = "Grid" runat="server" OnRowDeleting="OnRowDeleting" AutoGenerateColumns = "false" OnRowDataBound = "OnRowDataBound">
<Columns>
<asp:BoundField DataField="Code" HeaderText="Code" />
<asp:BoundField DataField="Course" HeaderText="Course" />
<asp:BoundField DataField="Credit" HeaderText="Credit" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
When I start to delete, I get this error:
check to determine if the object is null before calling the method
Error Reason
in OnRowDeleting function you are creating datatable and assigning viewstate["dt"],which doesn't have current data. that's why it shows Object is Null
Solution
Try This
First make one of the column as data key.consider i want to make "Code" column as datakey.
datakey will help to find specific row to delete
<asp:GridView ID="GridView1" CssClass = "Grid" runat="server" OnRowDeleting="OnRowDeleting" AutoGenerateColumns = "false" OnRowDataBound = "OnRowDataBound" DataKeyNames="Code">
After That in .cs code
create a datatable with currentdata
make "Code" column as primary key
find particular code(which you want to delete)using find()
then delete that row using delete() function
Reflect the deletion in viewsate["currentdata"]
then bind to gridview
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
string code = GridView1.DataKeys[e.RowIndex].Value.ToString();
if (ViewState["CurrentData"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentData"];
dt.PrimaryKey = new DataColumn[] { dt.Columns["Code"] };
dt.Rows.Find(code).Delete();
ViewState["CurrentData"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}

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

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