Why does my ASP.NET App show an extra table? - c#

This is a hybrid (MVC and Web forms) Web app to rate doctors. Here is my code for the ratings Web form. Why is there an extra table with the first record under the GridView? It happened after I pressed "Select" in the first row, but why does it stay there after I stop and run it again? It's not a cache problem, because it shows in different browsers. Thanks in advance!
<%# Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="Rating.aspx.cs" Inherits="MidtermApplication.Rating" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:ObjectDataSource ID="ObjectDataSourceDoctor" runat="server" DeleteMethod="Remove" InsertMethod="Add" SelectMethod="GetDoctor" TypeName="MidtermApplication.Models.TestApplicationDoctorRepo" UpdateMethod="Update" DataObjectTypeName="MidtermApplication.Models.Doctor">
</asp:ObjectDataSource>
<asp:GridView ID="GridViewDoctor" runat="server" DataSourceID="ObjectDataSourceDoctor" AutoGenerateColumns="False" OnSelectedIndexChanged="GridViewDoctor_SelectedIndexChanged">
<Columns>
<asp:ImageField DataImageUrlField="DoctorPicture" HeaderText="DoctorPicture">
</asp:ImageField>
<asp:BoundField DataField="DoctorName" HeaderText="DoctorName" SortExpression="DoctorName" />
<asp:BoundField DataField="DoctorSpecialty" HeaderText="DoctorSpecialty" SortExpression="DoctorSpecialty" />
<asp:TemplateField HeaderText="Rate Now">
<ItemTemplate>
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="RateNow" Text="1"></asp:RadioButton>
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="RateNow" Text="2"></asp:RadioButton>
<asp:RadioButton ID="RadioButton3" runat="server" GroupName="RateNow" Text="3"></asp:RadioButton>
<asp:RadioButton ID="RadioButton4" runat="server" GroupName="RateNow" Text="4"></asp:RadioButton>
<asp:RadioButton ID="RadioButton5" runat="server" GroupName="RateNow" Text="5"></asp:RadioButton>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField AccessibleHeaderText="Save Rating" HeaderText="Save Rating" Text="Save" />
<asp:CheckBoxField DataField="fave" HeaderText="Favorite" SortExpression="fave" InsertVisible="False" Visible="True" />
</Columns>
</asp:GridView>
</asp:Content>
Code behind:
namespace MidtermApplication
{
public partial class Rating : System.Web.UI.Page
{
TestApplicationDoctorRepo repo;
protected void Page_Load(object sender, EventArgs e)
{
TestApplicationDoctorRepo.InitApp(this);
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridViewDoctor_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}

Why is there an extra table with the first record under the GridView?
it is a details view, you can remove it in design mode in visual studio.
Update:
Solution:
You must create a new page, and design this page again.

Related

Hide/show gridview column based on role

Want to be able to set an "Edit" linkbutton to visible=false unless the user has a role of "Editor".
Been poking around stackoverflow and elsewhere and so far have not been able to get this to work.
Gridview:
<asp:GridView ID="GridView1" runat="server" Caption="Questions Awaiting Review" AllowSorting="True" PagerSettings-Mode="NumericFirstLast"
OnPageIndexChanging="GridView1_PageIndexChanging" CaptionAlign="Top" EmptyDataText="No Questions Pending Review."
PageSize="10" AllowPaging="true" PagerStyle-HorizontalAlign="Center" PagerStyle-Font-Size="Large" DataKeyNames="QuestionID"
OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#cccccc"
OnPreRender="GridView1_OnPreRender">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="250" />
<asp:BoundField DataField="SubmitDate" HeaderText="Submitted Date" ItemStyle-Width="60" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Details" CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="viewQuestion">View Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Edit" CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Have changed the code behind to use OnPreRender for the gridview, which if the value is hardcoded hides the column. However when I try to retrieve the is in role of editor then the value does not seem to be evaluating correctly. Always returns false even when the user has a role of Editor.
protected void GridView1_OnPreRender(object sender, EventArgs e)
{
if (Roles.IsUserInRole("Editor"))
{
// Enter correct column index.
GridView1.Columns[4].Visible = true;
}
else
{
GridView1.Columns[4].Visible = false;
}
}
Hoping I'm missing something simple, new to asp.net so not unlikely.
Hide last column.
this.GridView1.Columns[this.GridView1.Columns.Count - 1].Visible = Roles.IsUserInRole("Editor");
You want to show/hide an entire column instead of LinkButton control. Otherwise, unauthorized user will always see a column with blank cells which is odd.
The following example will hide an entire column.
Screen Shot (Authorize vs Unauthorized)
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1"
runat="server"
DataKeyNames="QuestionID"
OnPreRender="GridView1_OnPreRender"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="250" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Edit" CommandArgument='<%# Eval("QuestionID") %>'
runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
Code Behind
public class Question
{
public int QuestionID { get; set; }
public string KeyObjective { get; set; }
}
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = new List<Question>
{
new Question {QuestionID = 1, KeyObjective = "One"},
new Question {QuestionID = 2, KeyObjective = "Two"},
new Question {QuestionID = 3, KeyObjective = "Three"},
};
GridView1.DataBind();
}
}
protected void GridView1_OnPreRender(object sender, EventArgs e)
{
bool isEditor = true; // Business logic here
if (isEditor)
{
// Enter correct column index.
GridView1.Columns[2].Visible = false;
}
}
}
Use the LinkButton like this, with the Visibility property set from a function in code behind.
<asp:LinkButton ID="Edit" Visible='<%# ShowEditBasedOnRole() %>' CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
And then in code behind the function that returns a bool
public bool ShowEditBasedOnRole()
{
if (Roles.IsUserInRole("Editor"))
{
return true;
}
else
{
return false;
}
}
One quick modification instead of accessing the column by index. it can be accessed using header text which would not affect the code even if new column is inserted before the accessed column in future the code snippet
protected void grdResults_OnPreRender(object sender, EventArgs e)
{
TemplateField FieldToAccess= grdResults.Columns.OfType<TemplateField>
().Where(f => f.HeaderText ==
"ValidityDate").FirstOrDefault();
if (role)
FieldToAccess.Visible = false;
}

GridView Value Pass

I'm added a template field and made it a button click event. Then I'm trying to sent the value to event method and want to some operation with that value. I wrote following code. It has no compilation error but when i click Present browser shows following message:
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Code:
<div>
<asp:Panel ID="PanelAllEmployee" runat="server" Height="400px">
<asp:GridView ID="GridViewAllEmployee" runat="server" AutoGenerateColumns="False" style="position:absolute;left:219px; top:202px;" >
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Department" HeaderText="Department" />
<asp:BoundField DataField="EmailID" HeaderText="Email ID" />
<asp:BoundField DataField="Position" HeaderText="Position" />
<asp:TemplateField HeaderText="Present">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CommandArgument='<%#Eval("Id") %>' OnClick="Button1_Click" Text="Present" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="Label1" runat="server" Text="Label"> </asp:Label>
</asp:Panel>
</div>
Event Method:
protected void Button1_Click(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
string id = lnk.CommandArgument.ToString();
Label1.Text = id;
}
Please be kind to help me. I'm beginner. Elaborate answer is much appreciated. Thanks for your time.
set
EnableEventValidation="false" in the page directive in code-behind
for ex:
<%# Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
EDIT: .aspx :
<asp:Button ID="Button1" runat="server"
OnClick = "Button1_Click" CommandArgument='<%#Eval("Id") %>' Text="Present" />
cs code:
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string id = btn.CommandArgument.ToString();
}
using ButtonField and an OnRowCommand Event
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"
OnRowCommand = "OnRowCommand">
<Columns>
<asp:ButtonField CommandName = "ButtonField" DataTextField = "CustomerID"
ButtonType = "Button"/>
</Columns>
</asp:GridView>
Code Behind:
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}

GridView not filtering results

I am attaching a SqlDataSource to a grid view.
Inside my SqlDataSource I use control parameters to filter the data, I have a button to filter the data using the text inside the textboxes.
The main problem is that nothing is being filtered.
Here is my aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Main.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Template.Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head_breadcrumb" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentInfoBarName" runat="server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ContentInfoBarApprovalStatus" runat="server">
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="ContentInfoBarState" runat="server">
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="content" runat="server">
<tr>
<td width="100" align="right" bgcolor="#eeeeee" class="header1">Power Web</td>
<td align="center" bgcolor="#FFFFFF">
<asp:TextBox ID="txtNB" runat="server"></asp:TextBox>
<asp:TextBox ID="txtSystem" runat="server"></asp:TextBox>
<asp:TextBox ID="txtObjectID" runat="server"></asp:TextBox>
<asp:TextBox ID="txtObjectDescription" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" />
<asp:GridView ID="gvwExample" runat="server" OnClick="filter" AutoGenerateColumns="False" DataSourceID="GridDataSource" OnRowDataBound="gvwExample_RowDataBound" CssClass="basix" >
<columns>
<asp:BoundField DataField="NB" HeaderText="NB" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="CLevel" HeaderText="CLevel" />
<asp:BoundField DataField="CC Host" HeaderText="CC Host" />
<asp:BoundField DataField="System" HeaderText="System" />
<asp:BoundField DataField="Object Type" HeaderText="Object Type" />
<asp:BoundField DataField="Object ID" HeaderText="Object ID" />
<asp:BoundField DataField="Object Description" HeaderText="Object Description" />
<asp:BoundField DataField="Excl Mngr" HeaderText="Excl Mngr" />
</columns>
</asp:GridView>
<asp:SqlDataSource ID="GridDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:PowerWeb%>"
SelectCommand="SELECT * FROM Table1" FilterExpression="NB LIKE '{0}%' AND System LIKE '{1}%' AND Object ID LIKE '{2}%' AND Object Description LIKE '{3}%'">
<FilterParameters>
<asp:ControlParameter Name="NB" ControlID="txtNB" PropertyName="Text" Type="String" ConvertEmptyStringToNull="false" />
<asp:ControlParameter Name="System" ControlID="txtSystem" PropertyName="Text" Type="String" ConvertEmptyStringToNull="false" />
<asp:ControlParameter Name="Object ID" ControlID="txtObjectID" PropertyName="Text" Type="String" ConvertEmptyStringToNull="false" />
<asp:ControlParameter Name="Object Description" Type="String" ControlID="txtObjectDescription" PropertyName="Text" />
</FilterParameters>
</asp:SqlDataSource>
<asp:label ID="lblStatus" runat="server"></asp:label></td>
</tr>
</asp:Content>
And here is my code behind:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void gvwExample_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row, "Excl Mngr");
if (e.Row.Cells[index].Text == "False")
{
e.Row.Cells[index].Text = "";
}
else if(e.Row.Cells[index].Text == "True")
{
e.Row.Cells[index].Text = "Yes";
}
}
}
int GetColumnIndexByName(GridViewRow row, string SearchColumnName)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
{
if (((BoundField)cell.ContainingField).DataField.Equals(SearchColumnName))
{
break;
}
}
columnIndex++;
}
return columnIndex;
}
public void filter(Object sender, EventArgs e)
{
gvwExample.DataSource = GridDataSource;
gvwExample.DataBind();
}
}
EDIT:
The contentplaceholder named content is inside this on my master page:
<asp:UpdatePanel ID="updateMain" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<asp:ContentPlaceHolder ID="content" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
Is because this?
Have you tried to remove the UpdatePanel from the Master Page and add it to your page. Best practices recomend that you wrap your content with the update panel, only in the areas you need to update. This way you won't generate much traffic.
In this case, the UpdatePanel, won't bind well with the button inside the content/page, and like so, it won't trigger the update on the update panel.

add click on ASP.net

I am working on a college project and have a gridview that I have to add more rows to.
I have two text fields and a button.
Everything seems to be fine except the button part of the code in the .cs file
What am I doing wring?
Its to make a list of Wines with an ID and a Title and a Year:
Wine.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Wine.aspx.cs" Inherits="WineNotProject2.AdminPages.Wine" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<br /><br />
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Year" HeaderText="Year" SortExpression="Year" />
</Columns>
</asp:GridView>
<p><asp:Label ID="lblTitle" runat="server" Text="Wine Title"></asp:Label><br />
<asp:TextBox ID="txtTitle" runat="server" Width="176px"></asp:TextBox><br />
<p><asp:Label ID="lblYear" runat="server" Text="Wine Year"></asp:Label><br />
<asp:TextBox ID="txtYear" runat="server" Width="176px"></asp:TextBox><br />
</p>
<asp:Button ID="btnAdd" runat="server" Text="Add Wine" OnClick="btnAdd_Click" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [id], [Title], [Year] FROM [Wine]">
</asp:SqlDataSource>
</asp:Content>
Wine.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WineNotProject2.AdminPages
{
public partial class Wine : System.Web.UI.Page
{
private WineEntities10 ent2 = new WineEntities10();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RefreshGrid();
}
}
private void RefreshGrid()
{
GridView2.DataSource = ent2.Wines.ToList();
GridView2.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Wine w2 = new Wine();
w2.Title = txtTitle.Text;
w2.Year = txtYear.Text;
ent2.Wines.AddObject(w2);
ent2.SaveChanges();
}
}
}
UPDATE:
The error message is:
Error 3 'WineNotProject2.AdminPages.Wine' does not contain a definition for 'Year' and no extension method 'Year' accepting a first argument of type 'WineNotProject2.AdminPages.Wine' could be found (are you missing a using directive or an assembly reference?) C:\Visual Studio 2010\Projects\WineNotProject7\WineNotProject2\AdminPages\Wine.aspx.cs 30 20 WineNotProject2
I think you need to call RefreshGrid after you have added the new Wine:
protected void btnAdd_Click(object sender, EventArgs e)
{
Wine w2 = new Wine();
w2.Title = txtTitle.Text;
w2.Year = txtYear.Text;
ent2.Wines.AddObject(w2);
ent2.SaveChanges();
RefreshGrid(); // <-------
}
Maybe you also need to parse the year to int:
w2.Year = int.Parse(txtYear.Text);
The problem is you have two classes with same name Wine.
public partial class **Wine** : System.Web.UI.Page
**Wine** w2 = new **Wine**();
Rename ASP.Net page's name to WineList so that
its class name should become public partial class **WineList**
Your code was looking good ,But you miss call the RefreshGrid() end of add button
for
protected void btnAdd_Click(object sender, EventArgs e)
{
Wine w2 = new Wine();
w2.Title = txtTitle.Text;
w2.Year = txtYear.Text;
ent2.Wines.AddObject(w2);
ent2.SaveChanges();
**RefreshGrid**
}
If ent2.SaveChanges(); is not working ,then use ent2.SubmitChanges();

Asp.net buttons inside control inside gridview not working

I need to display a list of clients, but display them differently based on a parameter.
To do this, I have a gridvew, and inside there is a user control. That control has an "if" based on the type.
My problems:
If I add a button inside the control, when it is pressed I get a button validation error.
If I disable validation errors (enableEventValidation="false"), I get button commands to work, but I'm not able to change values on the control either with full postbacks or an updatepanel.
<asp:GridView ID="gvClients" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<xxx:ClientListGridItem ID="ClientListItem1" runat="server" Client='<%# ((Client) Container.DataItem) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
ClientListGridItem.ascx :
<% if (Client.Style >= 100)
{
%>
<div class="ClientListItem1">
...
<%
}
else
{
%>
<div class="ClientListItem2">
<asp:Button ID="Button2" runat="server" onclick="Button1_Click" Text="Button" />
...
<%
}
%>
I'm sure there is prettier, more object oriented way to do this too...
Changing ClientListGridItem.ascx into:
<asp:Panel id="Div1" CssClass="ClientListItem1" runat="server">
...
</asp:Panel>
<asp:Panel id="Div2" CssClass="ClientListItem2" runat="server">
<asp:Button ID="Button2" runat="server" onclick="Button1_Click" CausesValidation="false" Text="Button" />
..
</asp:Panel>
<script runat="server">
override void OnDataBinding(EventArgs e) {
Div1.Visible = Client.Style >= 100;
Div2.Visible = ! Div1.Visible;
}
</script>
should work.

Categories

Resources