Just starting with ASP.NET and find it difficult to use the GridView. I have a set of Session variables which I want to put into a GridView control, but I lack the knowledge. The file:
<%# Page Title="Warehouse" Language="C#" AutoEventWireup="true"
MasterPageFile="~/Site.master"
CodeFile="Warehouse.aspx.cs" Inherits="Warehouse" %>
<asp:Content ID="HeaderContent" runat="server"
ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Warehouse
</h2>
<asp:Panel ID="WarehousePanel" runat="server">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</asp:Panel>
</asp:Content>
In the code behind I want to add the session variables to the GridView1, just for display purposes. Later on it will be connected to a database, but for practice, I want to know how I can add my session variables to the GridView1. The file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Warehouse : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["milk"] == null)
Session["milk"] = "0";
if (Session["apple"] == null)
Session["apple"] = "0";
if (Session["orange"] == null)
Session["orange"] = "0";
// on page load, add session variables ie Session["milk"].ToString();
// column 1: inventory name
// column 2: inventory value
GridView1.?
}
}
I might be thinking this all wrong. If I do, please correct me to the right path! Thanx for listening.
It's as simple as putting this in your Page_Load:
// Sample to add a value to session to ensure that something is shown
Session.Add("SessionValue1", "Value");
// Actual work of binding Session to the grid
GridView1.DataSource = Session;
GridView1.DataBind();
There's a Microsoft Knowledge Base article that goes some way to answering your question(s) as it provides some examples of Data Binding in action and links to further articles giving additional detail.
Assuming you had some code such as:
var warehouseItems =
from item in DataTableContainingWarehouseItems.AsEnumerable()
select
new
{
InventoryName = item.Field<string>("Name"),
InventoryValue = item.Field<int>("Value"),
InventoryPrice = item.Field<decimal>("Price"),
StockOnHandValue = Convert.ToDecimal(item.Field<int>("Value") * item.Field<decimal>("Price"))
};
You could then bind directly to that:
GridView1.DataSource = warehouseItems;
GridView1.DataBind();
Related
I am trying to use gridview to display data from my database but I can't seem to get the gridview to display on the page. I inserted a breakpoint and the gridview shows the correct number of rows in the data source, and the correct number of rows in the gridview after databind. I am still not getting any display on the webpage, when inspecting where it should be with chrome I see the header tag but nothing related to the gridview. What am I doing wrong?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string id = Request.QueryString["profileID"];
GridView achievementTable = new GridView();
AchievementDatabaseTableAdapters.UserGamesTableAdapter UserGamesAdapter = new AchievementDatabaseTableAdapters.UserGamesTableAdapter();
AchievementDatabase.UserGamesDataTable userGames = UserGamesAdapter.GetUserGames();
achievementTable.DataSource = userGames.Select("ProfileID =" + id).CopyToDataTable();
achievementTable.DataBind();
}
}
.aspx code
<%# Page Title="Profile" Language="C#" AutoEventWireup="true" CodeBehind="Profile.aspx.cs"
MasterPageFile="~/Site.Master" Inherits="AchievementProject.Profile" %>
<asp:Content ID="ProfileContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %></h2>
<asp:Gridview ID="achievementTable" runat="server" AutoGenerateColumns="True"
ShowHeaderWhenEmpty="true" EmptyDataText="Failed"></asp:Gridview>
</asp:Content>
achievementTable is local to the page load event. Move it to at least a protected variable at the class level and it will be available to your views.
I'm working with a GridView and I am using a TableAdapter to communicate with my SQL Server 2017 Express. I have managed to display the table into a GridView but I would like to make the name of each entry in my database have a hyperlink that will direct the user to another page that contains a DetailsView that would allow the user to edit the corresponding entry. However, I am currently have troubles with the RowDataBoundEvent as it seemingly is not triggering.
When I set a breakpoint right at the if statement, the program does not stop at the breakpoint.
protected void ProductViewRowBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
string hyperLink = e.Row.Cells[1].Text;
e.Row.Cells[1].Text = "Test";
//HyperLink link = new HyperLink;
}
}
I checked my RowDataBound method name and it matches the one I specified in the aspx file:
<asp:GridView ID="ProductView" runat="server" Height="299px" Width="578px" AllowPaging="True" HorizontalAlign="Center"
OnRowDataBoundEvent="ProductViewRowBound" style="table-layout:auto">
<HeaderStyle Width="300px" />
</asp:GridView>
CS File:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Maintenance : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
ProductSetTableAdapters.Product_Table_AlphaTableAdapter productAdapter = new ProductSetTableAdapters.Product_Table_AlphaTableAdapter();
ProductView.DataSource = productAdapter.GetData();
ProductView.DataBind();
}
ProductView.RowDataBound += new GridViewRowEventHandler(ProductViewRowBound);
}
protected void ProductViewRowBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
string hyperLink = e.Row.Cells[1].Text;
e.Row.Cells[1].Text = "Test";
//HyperLink link = new HyperLink;
}
}
}
ASPX File:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Maintenance.aspx.cs" Inherits="Maintenance" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div style="overflow-x:scroll;overflow-y:scroll; margin-left:auto; margin-right:auto;">
<asp:GridView ID="ProductView" runat="server" Height="299px" Width="578px" AllowPaging="True" HorizontalAlign="Center"
OnRowDataBoundEvent="ProductViewRowBound" style="table-layout:auto">
<HeaderStyle Width="300px" />
</asp:GridView>
</div>
</asp:Content>
Why is my RowDataBoundEvent not running and what can I do to fix it?
First, OnRowDataBoundEvent does not exist. It should be OnRowDataBound in the GridView.
<asp:GridView ID="ProductView" runat="server" OnRowDataBound="ProductViewRowBound">
Next you are binding the correct method to the GridView from code behind, but AFTER you bind data to the GridView. So it will not work when you bind productAdapter.GetData().
So either set the correct event name in the GridView aspx or move the method binding above ProductView.DataBind();
How do I generate the controls in a div based on the markup defined in a SQL Server database? Is it possible? If yes, then how? Can anyone give me resources?
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="lit" runat="server" ClientIDMode="Static" Mode="Transform"></asp:Literal>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection _newConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand storedProcedure = new SqlCommand("sp_getMarkup", _newConnection);
storedProcedure.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(storedProcedure);
_newConnection.Open();
da.Fill(ds);
_newConnection.Close();
DataTable dt = ds.Tables["Table"];
string s = (from str in dt.AsEnumerable()
where str.Field<int>("Id").Equals(1)
select str.Field<string>("elemMarkup")).SingleOrDefault().ToString();
this.lit.Text = s;
}
}
}
In the database I have stored string as
<asp:CheckBox ID="chk" runat="server" ClientIDMode="Static" />
Now the problem is the control is rendered on page but is not visible. I can see it in view source.
Can anyone help me?
You can use ParseControl which accepts a string and create controls on the fly.
The drawback is if server code is in the string, it will not be executed. In addition, you need to attach event manually such as button click events.
For example,
<script runat="server">
// This server code will not be executed
</script>
Here is another SO question using jquery ajax to load info from database
I would recommend having some type of sanitizing intermediary; otherwise you are opening yourself up to cross-site scripting (XSS) issues.
You could use a placeholder on a page like so:
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
And in your code behind, you could have several checks (all of which contain SQL statements querying the data in the database). The database could contain a field containing component names such as checkbox, button (various other controls). This saves you storing markup in the database fields..
Very rough representation of how the code would look like..
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// SQL Code here
// Datatable code here
// End of DataTable code
// Beginning of IF blocks
If (DataTable.Rows.Count > 0) {
If (your check != "checkbox") {
this.PlaceHolder1.Controls.Add(new Button(){
Text = "Added"}
}
}
// More if statements here
);
}
}
Alternatively if you insist on storing asp markup in the database, then you could just feed the asp markup into the placeholder using a loop (if there are more than one rows in your database)
How do I generate the controls in a div based on the markup defined in a SQL Server database? Is it possible? If yes, then how? Can anyone give me resources?
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="lit" runat="server" ClientIDMode="Static" Mode="Transform"></asp:Literal>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection _newConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand storedProcedure = new SqlCommand("sp_getMarkup", _newConnection);
storedProcedure.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(storedProcedure);
_newConnection.Open();
da.Fill(ds);
_newConnection.Close();
DataTable dt = ds.Tables["Table"];
string s = (from str in dt.AsEnumerable()
where str.Field<int>("Id").Equals(1)
select str.Field<string>("elemMarkup")).SingleOrDefault().ToString();
this.lit.Text = s;
}
}
}
In the database I have stored string as
<asp:CheckBox ID="chk" runat="server" ClientIDMode="Static" />
Now the problem is the control is rendered on page but is not visible. I can see it in view source.
Can anyone help me?
You can use ParseControl which accepts a string and create controls on the fly.
The drawback is if server code is in the string, it will not be executed. In addition, you need to attach event manually such as button click events.
For example,
<script runat="server">
// This server code will not be executed
</script>
Here is another SO question using jquery ajax to load info from database
I would recommend having some type of sanitizing intermediary; otherwise you are opening yourself up to cross-site scripting (XSS) issues.
You could use a placeholder on a page like so:
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
And in your code behind, you could have several checks (all of which contain SQL statements querying the data in the database). The database could contain a field containing component names such as checkbox, button (various other controls). This saves you storing markup in the database fields..
Very rough representation of how the code would look like..
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// SQL Code here
// Datatable code here
// End of DataTable code
// Beginning of IF blocks
If (DataTable.Rows.Count > 0) {
If (your check != "checkbox") {
this.PlaceHolder1.Controls.Add(new Button(){
Text = "Added"}
}
}
// More if statements here
);
}
}
Alternatively if you insist on storing asp markup in the database, then you could just feed the asp markup into the placeholder using a loop (if there are more than one rows in your database)
I am using C# ASP.NET , i did a crosspage postback and it is working fine, without master page.
But while using Master page , same logic fails and get the error described above. I am new to ASP.NET, please tell me in little detail.
My code is
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="View_Information.aspx.cs" Inherits="View_Information" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<p>
Module 3: Assignment 1</p>
<div>
Total Data You Have Entered
<br />
<br />
Name:
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<br />
Address:
<asp:Label ID="Label2" runat="server"></asp:Label>
<br />
<br />
Thanks for submitting your data.<br />
</div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="Placehodler2" Runat="Server">
</asp:Content>
And code behind is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class View_Information : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null && PreviousPage.IsPostBack)
{
TextBox nametextpb = (TextBox)PreviousPage.FindControl("TextBox1");
//Name of controls should be good to identify in case application is big
TextBox addresspb = (TextBox)PreviousPage.FindControl("TextBox2");
Label1.Text = nametextpb.Text; //exception were thrown here
Label2.Text = addresspb.Text;
}
else
{
Response.Redirect("Personal_Information.aspx");
}
}
}
The problem is that, with the master page, your controls are now required to be placed in the ContentPlaceHolder controls.
The FindControl method can be used to access a control whose ID is not
available at design time. The method searches only the page's
immediate, or top-level, container; it does not recursively search for
controls in naming containers contained on the page. To access
controls in a subordinate naming container, call the FindControl
method of that container.
You now need to recursively search through the controls to find your TextBox controls from the PreviousPage. You can see an example of that here. Also noted on that site, you can get the control by its full UniqueID, which in your case will work via:
TextBox nametextpb = (TextBox)PreviousPage.FindControl("ctl00$ContentPlaceHolder1$TextBox1")
EDIT: Figured it couldn't hurt to include the code I used to locate the UniqueID of the target control.
In Page_Load:
var ids = new List<string>();
BuildControlIDListRecursive(PreviousPage.Controls, ids);
And the method definition:
private void BuildControlIDListRecursive(ControlCollection controls, List<string> ids)
{
foreach (Control c in controls)
{
ids.Add(string.Format("{0} : {2}", c.ID, c.UniqueID));
BuildControlIDListRecursive(c.Controls, ids);
}
}
Then just locate your control from the ids list.
(TextBox)PreviousPage.FindControl("TextBox1"); must have returned null, which means that the control was not found.
Try using Page.Master.FindControl() instead.