GridView not displaying on webpage - c#

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.

Related

GridView RowDataBoundEvent not running

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

ASP.NET web forms user control with DropDownList's SelectedIndex cannot be set

I have created a web forms user control with a DropDownList. I want to change SelectedIndex property of DropDownList1 to change the selected index.
WebUserControl1.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.ControlUI.WebUserControl1" %>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
WebUserControl1.ascx.cs:
using System;
namespace WebApplication1.ControlUI
{
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e) {
if (IsPostBack) return;
for (int i = 1; i <= 5; i++) {
DropDownList1.Items.Add("Test: " + i.ToString());
}
}
public void SetSelectedIndex(int index) {
DropDownList1.SelectedIndex = index;
}
}
}
Now I am using the user control in a page.
Default.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<%# Register Src="~/ControlUI/WebUserControl1.ascx" TagPrefix="uc1" TagName="WebUserControl1" %>
<asp:Content ID="HeadContent" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<uc1:WebUserControl1 runat="server" id="WebUserControl1" />
</asp:Content>
Default.aspx.cs:
using System;
using System.Web.UI;
namespace WebApplication1
{
public partial class Default : Page
{
protected void Page_Load(object sender, EventArgs e) {
WebUserControl1.SetSelectedIndex(3);
}
}
}
This does not work. It assigns -1 into SelectedIndex property of DropDownList1. But the user control works if I add items into the DropDownList in the markup (WebUserControl1.ascx), rather than in the codebehind file (WebUserControl1.ascx.cs):
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.ControlUI.WebUserControl1" %>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Test: 1</asp:ListItem>
<asp:ListItem>Test: 2</asp:ListItem>
<asp:ListItem>Test: 3</asp:ListItem>
<asp:ListItem>Test: 4</asp:ListItem>
<asp:ListItem>Test: 5</asp:ListItem>
</asp:DropDownList>
But I need to add items using the codebehind file, not in the markup file. Why it is not working? How to solve the problem?
The issue is that Page_Load for the page containing the user control (Default) executes before Page_Load for the user control (WebUserControl1). Therefore, when SetSelectedIndex is invoked from the page, the drop down does not have any list item in it when the page is first built.
You can solve the issue very simply by creating the list item for the drop down in the Init stage of the user control life cycle rather than in the Load stage:
protected void Page_Init(object sender, EventArgs e) {
if (IsPostBack) return;
for (int i = 1; i <= 5; i++) {
DropDownList1.Items.Add("Test: " + i.ToString());
}
}

How do i manipulate a string/dataitem in my Listview?

This is how i am showing the string in listview:
<%# Eval("Description")%>
This is the code in a method to get the data for listview :
lstBlog.DataSource = blg;
lstBlog.DataBind();
How can i manipulate the "Description" string ... i.e. get only first 50 characters/stripping off any html tags from the string .......
Thanx in advance
in aspx page
<%# CutString(Eval("Description").ToString(),50) %>
in cs
public string CutString(string value , int len)
{
// ....
}
In aspx page, you can directly take string part as below:
<%# Convert.ToString(Eval("Description")).Substring(0, 50) %>
"OR"
In aspx page and create ItemDataBound event for the ListView
<asp:Label ID="lblDescription" runat="server" Text=""></asp:Label>
In code behind, create ItemDataBound
protected void lvData_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Blog blg = (Blog)e.Item.DataItem;
Label lblDescription = (Label)e.Item.FindControl("lblDescription");
lblDescription.Text = blg.Description.Substring(0, 50);
}
}
To strip HTML tags please see here: http://www.dotnetperls.com/remove-html-tags

Display Session variables in GridView (ASP.NET)?

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

ASP.NET Panel FindControl within DataList to change property C#

I'm new to this ASP.NET stuff. In my page I have a Datalist with a FooterTemplate. In the footer I have a couple panels that will be visible depending on the QueryString. The problem I am having is trying to find these panels on Page_Load to change the Visible Property. Is there a way to find this control in the Page_Load? For example this is part of the aspx page:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:DataList ID="dlRecords" runat="server">
<FooterTemplate>
<asp:Panel ID="pnlArticleHeader" runat="server" Visible="false" >
</asp:Panel>
</FooterTemplate>
</asp:Datalist>
</asp:Content>
Here is something in the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
location = Request.QueryString["location"];
if (location == "HERE")
{
Panel pnlAH = *Need to find control here*;
pnlAH.Visible=true;
}
}
Like I said I am new at this. Everything I have found doesn't seem to work so I decided to post a specific question. Thanks in advance
DataList has event OnItemCreated, overriding allows select type of row:
Panel _pnlArticleHeader;
void Item_Created(Object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
_pnlArticleHeader =(Panel)e.Item.FindControl("pnlArticleHeader");
}
}
After event invocation in the field: _pnlArticleHeader you will get desired panel. This way is safe since created only once. NOTE! same way for common DataList's row would return only last one.

Categories