I've just taken over a C#/.NET project last touched a few years ago with with the task of updating it and including more functionality. I have no experience with the platform and so am struggling to fix this error.
The system is currently live (and works), but I've gotten a copy running on my machine and I get the following error which I cannot seem to figure out to get it up and running:
Compiler Error Message: CS0120: An object reference is required for the non-static field, method, or property '<ProjectName>.<PageName>.System'
Source Error:
Line 195:
Line 196: private static System.Reflection.MethodInfo #__PageInspector_LoadHelper(string helperName) {
Line 197: System.Type helperClass = System.Type.GetType("Microsoft.VisualStudio.Web.PageInspector.Runtime.WebForms.TraceHelpers, Microsoft" +
Line 198: ".VisualStudio.Web.PageInspector.Tracing, Version=2.0.0.0, Culture=neutral, Publi" +
Line 199: "cKeyToken=b03f5f7f11d50a3a", false, false);
I've established from other questions that this error is normally caused when using non-static fields and methods incorrectly like this or this, but in my case it seems to be coming from a temporary file, which I have no control over?
UPDATE: The Admin.aspx file is below:
<%# Page Title="" Language="C#" MasterPageFile="~/Admin/Admin.Master" AutoEventWireup="false"
EnableEventValidation="false" CodeBehind="Admin.aspx.cs" Inherits="CallLog.Admin" %>
<asp:Content ID="Content1" ContentPlaceHolderID="AdminContent1" runat="server">
<div id="System" class="SectionTitle" runat="server">
<table cellpadding="1px" cellspacing="1px">
<tr>
<td class="SectionTitleTd">
<i>SYSTEM</i>
</td>
</tr>
</table>
</div>
<table>
<tr>
<td>
<asp:TextBox ID="txtAddAppSystem" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="btnAddAppSystem" CssClass="Save" runat="server" Text="Add New System"
OnClick="btnAddAppSystem_Click" ValidationGroup="appsystem" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ValidationGroup="appsystem" ControlToValidate="txtAddAppSystem" ErrorMessage="Please Add System" CssClass="Warning"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvAppSystem" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="White"
BorderColor="Gray" DataKeyNames="AppSystemId" OnRowCancelingEdit="gvAppSystem_RowCancelingEdit"
OnRowEditing="gvAppSystem_RowEditing" OnRowUpdating="gvAppSystem_RowUpdating">
<AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="appSystemId" HeaderText="ID" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="System" ItemStyle-Width="150px">
<ItemTemplate>
   
<%# Eval("appSystemDesc")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtAppSystem" Text='' value='<%# Eval ("appSystemDesc") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="AdminContent2" runat="server">
<div id="Div1" class="SectionTitle" runat="server">
<table cellpadding="1px" cellspacing="1px">
<tr>
<td class="SectionTitleTd">
<i>STATUS</i>
</td>
</tr>
</table>
</div>
<table>
<tr>
<td>
<asp:TextBox ID="txtAddStatus" runat="server" Width="200px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ValidationGroup="status" runat="server" ControlToValidate="txtAddStatus" ErrorMessage="Please Add Status" CssClass="Warning"></asp:RequiredFieldValidator>
<asp:Button ID="btnAddStatus" CssClass="Save" runat="server" ValidationGroup="status" Text="Add New Status"
OnClick="btnAddStatus_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvStatus" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="White"
BorderColor="Gray" DataKeyNames="statusId" OnRowCancelingEdit="gvStatus_RowCancelingEdit"
OnRowEditing="gvStatus_RowEditing" OnRowUpdating="gvStatus_RowUpdating">
<AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="statusId" HeaderText="ID" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="Status" ItemStyle-Width="150px">
<ItemTemplate>
   
<%# Eval("statusDesc") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtStatus" Text='' value='<%# Eval ("statusDesc") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="AdminContent3" runat="server">
<div id="Jurisdiction" class="SectionTitle" runat="server">
<table cellpadding="1px" cellspacing="1px">
<tr>
<td class="SectionTitleTd">
<i>JURISDICTION</i>
</td>
</tr>
</table>
</div>
<div>
<table>
<tr>
<td>
<asp:TextBox ID="txtAddJurisdiction" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="btnAddJurisdiction" CssClass="Save" runat="server" ValidationGroup="juridiction" Text="Add New Jurisdiction"
OnClick="btnAddJurisdiction_Click" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ValidationGroup="juridiction" ControlToValidate="txtAddJurisdiction" ErrorMessage="Please Add Juridiction" CssClass="Warning"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvJurisdiction" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="White"
BorderColor="Gray" DataKeyNames="jurisdictionId" OnRowCancelingEdit="gvJurisdiction_RowCancelingEdit"
OnRowEditing="gvJurisdiction_RowEditing" OnRowUpdating="gvJurisdiction_RowUpdating">
<AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="jurisdictionId" HeaderText="ID" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="Jurisdiction" ItemStyle-Width="150px">
<ItemTemplate>
   
<%# Eval("jurisdictionDesc") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtJurisdiction" Text='' value='<%# Eval ("jurisdictionDesc") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="AdminContent4" runat="server">
<div id="Impact" class="SectionTitle" runat="server">
<table cellpadding="1px" cellspacing="1px">
<tr>
<td class="SectionTitleTd">
<i>IMPACT</i>
</td>
</tr>
</table>
</div>
<div>
<table>
<tr>
<td>
<asp:TextBox ID="txtImpact" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="btnImpact" CssClass="Save" runat="server" Text="Add New Impact" ValidationGroup="impact" OnClick="btnAddImpact_Click" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtImpact" ValidationGroup="impact" ErrorMessage="Please Add Impact" CssClass="Warning"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvImpact" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="White"
BorderColor="Gray" DataKeyNames="impactId" OnRowCancelingEdit="gvImpact_RowCancelingEdit"
OnRowEditing="gvImpact_RowEditing" OnRowUpdating="gvImpact_RowUpdating">
<AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="impactId" HeaderText="ID" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="Impact" ItemStyle-Width="150px">
<ItemTemplate>
   
<%# Eval("impactDesc") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtImpact" Text='' value='<%# Eval ("impactDesc") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="AdminContent5" runat="server">
<div id="Period" class="SectionTitle" runat="server">
<table cellpadding="1px" cellspacing="1px">
<tr>
<td class="SectionTitleTd">
<i>PERIOD</i>
</td>
</tr>
</table>
</div>
<div>
<table>
<tr>
<td>
<asp:TextBox ID="txtAddPeriod" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="btnAddPeriod" CssClass="Save" runat="server" ValidationGroup="period" Text="Add New Period"
OnClick="btnAddPeriod_Click" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ValidationGroup="period" ControlToValidate="txtAddPeriod" ErrorMessage="Please Add Period" CssClass="Warning"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvPeriod" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="White"
BorderColor="Gray" DataKeyNames="periodId" OnRowCancelingEdit="gvPeriod_RowCancelingEdit"
OnRowEditing="gvPeriod_RowEditing" OnRowUpdating="gvPeriod_RowUpdating">
<AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="periodId" HeaderText="ID" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="Period" ItemStyle-Width="150px">
<ItemTemplate>
   
<%# Eval("periodDesc") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtPeriod" Text='' value='<%# Eval ("periodDesc") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="AdminContent6" runat="server">
<div id="Issue" class="SectionTitle" runat="server">
<table cellpadding="1px" cellspacing="1px">
<tr>
<td class="SectionTitleTd">
<i>ISSUE</i>
</td>
</tr>
</table>
</div>
<div>
<table>
<tr>
<td>
<asp:TextBox ID="txtAddIssue" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="btnAddIssue" CssClass="Save" runat="server" ValidationGroup="issue" Text="Add New Issue"
OnClick="btnAddIssue_Click" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ValidationGroup="issue" ControlToValidate="txtAddIssue" ErrorMessage="Please Add Issue" CssClass="Warning"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvIssue" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="White"
BorderColor="Gray" DataKeyNames="issueId" OnRowCancelingEdit="gvIssue_RowCancelingEdit"
OnRowEditing="gvIssue_RowEditing" OnRowUpdating="gvIssue_RowUpdating">
<AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="issueId" HeaderText="ID" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="Issue" ItemStyle-Width="150px">
<ItemTemplate>
   
<%# Eval("issueDesc")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtIssue" Text='' value='<%# Eval ("issueDesc") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</asp:Content>
UPDATE 2: The Admin.aspx.cs file below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Midtier.DAL;
namespace CallLog
{
public partial class Admin : System.Web.UI.Page
{
AdminDisplay ad = new AdminDisplay();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
listJurisdictions();
listImpact();
listStatus();
listPeriod();
listAppSystem();
listIssue();
}
}
#region AppSystem
public void listAppSystem()
{
gvAppSystem.DataSource = ad.getAppSystem();
gvAppSystem.DataBind();
}
protected void gvAppSystem_RowEditing(object sender, GridViewEditEventArgs e)
{
btnAddAppSystem.Enabled = false;
gvAppSystem.EditIndex = e.NewEditIndex;
listAppSystem();
}
protected void gvAppSystem_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
gvAppSystem.EditIndex = -1;
listAppSystem();
}
protected void gvAppSystem_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvAppSystem.Rows[e.RowIndex];
TextBox txtAppSystemDesc = (TextBox)row.FindControl("txtAppSystem");
int appSystemID = Int32.Parse(gvAppSystem.DataKeys[e.RowIndex].Value.ToString());
string appSystemDesc = txtAppSystemDesc.Text;
AdminUpdates au = new AdminUpdates();
au.AddEditAppSystem(appSystemID, appSystemDesc);
gvAppSystem.EditIndex = -1;
listAppSystem();
btnAddAppSystem.Enabled = true;
}
protected void btnAddAppSystem_Click(object sender, EventArgs e)
{
AdminUpdates au = new AdminUpdates();
au.AddEditAppSystem(-1, txtAddAppSystem.Text);
listAppSystem();
txtAddStatus.Text = "";
}
#endregion
#region Status
public void listStatus()
{
gvStatus.DataSource = ad.getStatus();
gvStatus.DataBind();
}
protected void gvStatus_RowEditing(object sender, GridViewEditEventArgs e)
{
btnAddStatus.Enabled = false;
gvStatus.EditIndex = e.NewEditIndex;
listStatus();
}
protected void gvStatus_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
gvStatus.EditIndex = -1;
listStatus();
}
protected void gvStatus_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvStatus.Rows[e.RowIndex];
TextBox txtStatusDesc = (TextBox)row.FindControl("txtStatus");
int statusID = Int32.Parse(gvStatus.DataKeys[e.RowIndex].Value.ToString());
string statusDesc = txtStatusDesc.Text;
AdminUpdates au = new AdminUpdates();
au.AddEditStatus(statusID, statusDesc);
gvStatus.EditIndex = -1;
listStatus();
btnAddStatus.Enabled = true;
}
protected void btnAddStatus_Click(object sender, EventArgs e)
{
AdminUpdates au = new AdminUpdates();
au.AddEditStatus(-1, txtAddStatus.Text);
listStatus();
txtAddStatus.Text = "";
}
#endregion
#region Jurisdiction
private void listJurisdictions()
{
gvJurisdiction.DataSource = ad.getJurisdiction();
gvJurisdiction.DataBind();
}
protected void gvJurisdiction_RowEditing(object sender, GridViewEditEventArgs e)
{
btnAddJurisdiction.Enabled = false;
gvJurisdiction.EditIndex = e.NewEditIndex;
listJurisdictions();
}
protected void gvJurisdiction_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
gvJurisdiction.EditIndex = -1;
listJurisdictions();
}
protected void gvJurisdiction_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvJurisdiction.Rows[e.RowIndex];
TextBox txtJurisdictionDesc = (TextBox)row.FindControl("txtJurisdiction");
int jurisdictionID = Int32.Parse(gvJurisdiction.DataKeys[e.RowIndex].Value.ToString());
string jurisdictionDesc = txtJurisdictionDesc.Text;
AdminUpdates au = new AdminUpdates();
au.AddEditJurisdiction(jurisdictionID, jurisdictionDesc);
gvJurisdiction.EditIndex = -1;
listJurisdictions();
btnAddJurisdiction.Enabled = true;
}
protected void btnAddJurisdiction_Click(object sender, EventArgs e)
{
AdminUpdates au = new AdminUpdates();
au.AddEditJurisdiction(-1, txtAddJurisdiction.Text);
listJurisdictions();
txtAddJurisdiction.Text = "";
}
#endregion
#region Impact
private void listImpact()
{
gvImpact.DataSource = ad.getImpact();
gvImpact.DataBind();
}
protected void gvImpact_RowEditing(object sender, GridViewEditEventArgs e)
{
btnImpact.Enabled = false;
gvImpact.EditIndex = e.NewEditIndex;
listImpact();
}
protected void gvImpact_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
gvImpact.EditIndex = -1;
listImpact();
}
protected void gvImpact_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvImpact.Rows[e.RowIndex];
TextBox txtImpactDesc = (TextBox)row.FindControl("txtImpact");
int impactID = Int32.Parse(gvImpact.DataKeys[e.RowIndex].Value.ToString());
string impactDesc = txtImpactDesc.Text;
AdminUpdates au = new AdminUpdates();
au.AddEditImpact(impactID, impactDesc);
gvImpact.EditIndex = -1;
listImpact();
btnImpact.Enabled = true;
}
protected void btnAddImpact_Click(object sender, EventArgs e)
{
AdminUpdates au = new AdminUpdates();
au.AddEditImpact(-1, txtImpact.Text);
listImpact();
txtImpact.Text = "";
}
#endregion
#region Period
private void listPeriod()
{
gvPeriod.DataSource = ad.getPeriod();
gvPeriod.DataBind();
}
protected void gvPeriod_RowEditing(object sender, GridViewEditEventArgs e)
{
btnAddPeriod.Enabled = false;
gvPeriod.EditIndex = e.NewEditIndex;
listPeriod();
}
protected void gvPeriod_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
gvPeriod.EditIndex = -1;
listPeriod();
}
protected void gvPeriod_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvPeriod.Rows[e.RowIndex];
TextBox txtPeriodDesc = (TextBox)row.FindControl("txtPeriod");
int periodID = Int32.Parse(gvPeriod.DataKeys[e.RowIndex].Value.ToString());
string periodDesc = txtPeriodDesc.Text;
AdminUpdates au = new AdminUpdates();
au.AddEditPeriod(periodID, periodDesc);
gvPeriod.EditIndex = -1;
listPeriod();
btnAddPeriod.Enabled = true;
}
protected void btnAddPeriod_Click(object sender, EventArgs e)
{
AdminUpdates au = new AdminUpdates();
au.AddEditPeriod(-1, txtAddPeriod.Text);
listPeriod();
txtAddPeriod.Text = "";
}
#endregion
#region Issue
private void listIssue()
{
gvIssue.DataSource = ad.getIssue();
gvIssue.DataBind();
}
protected void gvIssue_RowEditing(object sender, GridViewEditEventArgs e)
{
btnAddIssue.Enabled = false;
gvIssue.EditIndex = e.NewEditIndex;
listIssue();
}
protected void gvIssue_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
gvIssue.EditIndex = -1;
listIssue();
}
protected void gvIssue_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvIssue.Rows[e.RowIndex];
TextBox txtIssueDesc = (TextBox)row.FindControl("txtIssue");
int issueID = Int32.Parse(gvIssue.DataKeys[e.RowIndex].Value.ToString());
string issueDesc = txtIssueDesc.Text;
AdminUpdates au = new AdminUpdates();
au.AddEditIssue(issueID, issueDesc);
gvIssue.EditIndex = -1;
listIssue();
btnAddIssue.Enabled = true;
}
protected void btnAddIssue_Click(object sender, EventArgs e)
{
AdminUpdates au = new AdminUpdates();
au.AddEditIssue(-1, txtAddIssue.Text);
listIssue();
txtAddIssue.Text = "";
}
#endregion
}
}
I think, you are having same name for both class and namespace, could you please check, it might be the cause of this issue.
As, usual, I found the solution to my own problem (two cups of coffee and eight full hours of sleep later - not in that order).
The problem was that in Admin.aspx, the first div with id=System forced the Admin.aspx.designer.cs file to generate a System.Web.UI.HtmlControls.HtmlGenericControl variable called System.
This caused some sort of confusion for the compiler (is that even an actual thing?) because of the System namespace.
This was a good lesson in what not to do.
Related
What I'm trying to Achieve
I have a ASP.NET Telerik RadGrid. I want it to sort by column when I press a column header.
Problem
When I press a column header to sort the grid, the grid is cleared and all rows disappear and after the text "No records to display" is shown.
After pressing the Status column header:
Code
The .aspx code (template):
<%# Page MasterPageFile="~/MyApp.Master" Async="True" Language="C#" AutoEventWireup="true" CodeBehind="SecondLine.aspx.cs" Inherits="MyApp_Service_WEB.SecondLine" %>
<asp:Content id="SecondLineContent" ContentPlaceHolderId="content" runat="server">
<style>
.small-top-margin {
margin-top: 0.5em;
}
.medium-top-margin {
margin-top: 1em;
}
.medium-bottom-margin {
margin-bottom: 1em;
}
.vertical-center {
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
}
.auto-width {
width: auto;
min-width: auto;
max-width: auto;
}
</style>
<!-- Search section -->
<div class="col-12">
<fieldset>
<legend>
<asp:Literal id="lSearchTitle" Text="<%$ Resources:Global, SearchCase %>" runat="server" />
</legend>
<div class="col-12">
<!-- Status select -->
<div class="row">
<asp:Label id="lbStatusSelect" runat="server" Text="<%$ Resources:Global, Status %>"/>
</div>
<div class="row small-top-margin">
<asp:DropDownList id="ddlStatusSelect" DataTextField="Description" DataValueField="Id" CssClass="select-md auto-width" runat="server"></asp:DropDownList>
</div>
<!-- Check boxes -->
<div class="row medium-top-margin vertical-center">
<asp:CheckBox id="chPersonalInjury" runat="server"></asp:CheckBox>
<asp:Label id="lbPersonalInjury" Text="<%$ Resources:Global, PersonalInjury %>" runat="server" />
</div>
<div class="row vertical-center">
<asp:CheckBox id="chRiskForPersonalInjury" runat="server"></asp:CheckBox>
<asp:Label id="lbRiskForPersonalInjury" Text="<%$ Resources:Global, RiskForPersonalInjury %>" runat="server" />
</div>
<div class="row vertical-center">
<asp:CheckBox id="chCompensationDemand" runat="server"></asp:CheckBox>
<asp:Label id="lbCompensationDemand" Text="<%$ Resources:Global, CompensationDemand %>" runat="server" />
</div>
<div class="row vertical-center">
<asp:CheckBox id="chSecondLine" runat="server"></asp:CheckBox>
<asp:Label id="lbSecondLine" Text="<%$ Resources:Global, SecondLine %>" runat="server" />
</div>
<div class="row medium-top-margin medium-bottom-margin">
<asp:Button id="btnSearch" UseSubmitBehaviour="True" CssClass="button grey" Text="<%$ Resources:Global, ButtonSearch %>" runat="server" OnClick="btnSearch_Click"></asp:Button>
<asp:button id="btnCancel" UseSubmitBehaviour="True" CssClass="button grey" Text="<%$ Resources:Global, ButtonCancel %>" runat="server" OnClick="btnCancel_Click"></asp:button>
</div>
</div>
</fieldset>
</div>
<!-- Result section -->
<div class="col-12">
<fieldset>
<legend>
<asp:Literal id="lResultTitle" Text="<%$ Resources:Global, BlockHeaderText2 %>" runat="server" />
</legend>
<telerik:RadGrid ID="rgCases" CssClass="data-table bottomSpace" runat="server" AutoGenerateColumns="False" Skin="Metro"
ForeColor="#333333" CellPadding="4" ShowFooter="false" GridLines="None" Width="100%"
AllowSorting="True"
OnNeedDataSource="rgCases_OnNeedDataSource"
OnSortCommand="rgCases_Sorting"
OnItemDataBound="rgCases_OnItemDataBound"
OnSelectedIndexChanged="rgCases_OnSelectedIndexChanged">
<ClientSettings EnablePostBackOnRowClick="True" Selecting-AllowRowSelect="true" Scrolling-SaveScrollPosition="true"
Scrolling-AllowScroll="true" Scrolling-UseStaticHeaders="true" EnableRowHoverStyle="true">
</ClientSettings>
<MasterTableView DataKeyNames="CaseId, ArticleNumber, ArticleDescription, CaseType, Status, Language, Created" ShowHeadersWhenNoRecords="true">
<Columns>
<telerik:GridTemplateColumn SortExpression="CaseId">
<HeaderTemplate>
<asp:Label ID="CaseIdHeader" runat="server" Text="<%$ Resources:Global, CaseNumberColumn %>"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="CaseIdItem" runat="server" Text='<%# Bind("CaseId") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="10em" />
<HeaderStyle Width="10em" />
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn SortExpression="ArticleNumber">
<HeaderTemplate>
<asp:Label ID="ArticleNumberHeader" runat="server" Text="<%$ Resources:Global, ArticleNr %>"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="ArticleNumberItem" runat="server" Text='<%# Bind("ArticleNumber") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="10em" />
<HeaderStyle Width="10em" />
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="ArticleDescription" HeaderText="<%$ Resources:Global, Description %>" UniqueName="ArticleDescription" HeaderStyle-HorizontalAlign="Left" SortExpression="ArticleDescription" />
<telerik:GridBoundColumn DataField="CaseType" HeaderText="<%$ Resources:Global, CaseType %>" UniqueName="CaseType" HeaderStyle-HorizontalAlign="Left" />
<telerik:GridBoundColumn DataField="Status" HeaderText="<%$ Resources:Global, Status %>" UniqueName="Status" HeaderStyle-HorizontalAlign="Left" SortExpression="Status" />
<telerik:GridTemplateColumn SortExpression="Language">
<HeaderTemplate>
<asp:Label ID="LanguageHeader" runat="server" Text="<%$ Resources:Global, Country %>"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="LanguageItem" runat="server" Text='<%# Bind("Language") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="5em" />
<HeaderStyle Width="5em" />
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn SortExpression="Created">
<HeaderTemplate>
<asp:Label ID="CreatedHeader" runat="server" Text="<%$ Resources:Global, CreatedOn %>"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="CreatedItem" runat="server" Text='<%# Bind("Created") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="13em" />
<HeaderStyle Width="13em" />
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</fieldset>
</div>
</asp:Content>
The .cs code (code behind):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyApp_WCF.CASEDB;
using MyApp_WCF.DataContracts;
using MyApp_WCF.Helpers;
using Telerik.Web.UI;
namespace MyApp_Service_WEB
{
public partial class SecondLine : BasePage
{
public List<WorkFlowRowStatus> StatusList { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateControls();
SetControlDefaultValues();
InitCasesLoad();
}
}
private void PopulateControls() {
RegisterAsyncTask(new PageAsyncTask(PopulateStatusSelect));
}
private void SetControlDefaultValues() {
chSecondLine.Checked = true;
}
private async Task PopulateStatusSelect() {
await LoadStatusList();
ddlStatusSelect.DataSource = StatusList;
ddlStatusSelect.DataBind();
}
private async Task LoadStatusList() {
if(StatusList != null)
return;
SemiStaticSettingsCache semiStaticSettingsCache = new SemiStaticSettingsCache();
StatusList = (await semiStaticSettingsCache.GetWorkFlowRowStatusesAsync(GetSetting().UserInformation.GetCultureNameByUserLanguage()))
.Select(s => s).ToList();
WorkFlowRowStatus emptyOption = new WorkFlowRowStatus{
Id = -1,
Description = ""
};
StatusList.Insert(0, emptyOption);
}
private void InitCasesLoad()
{
RegisterAsyncTask(new PageAsyncTask(SearchCases));
}
protected async void btnSearch_Click(object sender, EventArgs eventArgs)
{
await SearchCases();
}
protected void btnCancel_Click(object sender, EventArgs eventArgs)
{
}
protected void rgCases_Sorting(object sender, GridSortCommandEventArgs e)
{
GridTableView caseTable = e.Item.OwnerTableView;
GridSortExpression sortExpression = new GridSortExpression
{
FieldName = e.SortExpression,
SortOrder = e.NewSortOrder
};
caseTable.SortExpressions.AddSortExpression(sortExpression);
caseTable.Rebind();
}
protected void rgCases_OnItemDataBound(object sender, GridItemEventArgs e)
{
}
protected void rgCases_OnSelectedIndexChanged(object sender, EventArgs e)
{
SecondLineTableRow selectedCase = GetSelectedGridRow();
int? caseId = selectedCase.CaseId;
Response.Redirect($"WorkWithCase.aspx?chid={caseId}");
}
protected void rgCases_OnNeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
rgCases.DataSource = new List<SecondLineTableRow>();
}
private void SetGridRows(List<SecondLineTableRow> rows)
{
rgCases.DataSource = rows;
rgCases.DataBind();
}
private SecondLineTableRow GetSelectedGridRow()
{
try
{
GridItem selectedItem = rgCases.SelectedItems[0];
SecondLineTableRow selectedRow = GetRowFromGridItem(selectedItem);
return selectedRow;
}
catch (Exception)
{
return null;
}
}
private SecondLineTranslations GetSecondLineTranslations() {
return new SecondLineTranslations(
GetGlobalResourceObject("Global", "PersonalInjury") as string,
GetGlobalResourceObject("Global", "RiskForPersonalInjury") as string,
GetGlobalResourceObject("Global", "CompensationDemand") as string,
GetGlobalResourceObject("Global", "SecondLine") as string,
GetGlobalResourceObject("Global", "Repair") as string
);
}
private async Task SearchCases() {
SecondLineTranslations secondLineTranslations = GetSecondLineTranslations();
SecondLineRepository secondLineRepo = new SecondLineRepository(secondLineTranslations);
SecondLineSearchCriteria searchCriteria = CreateSearchCriteria();
List<SecondLineTableRow> cases = await secondLineRepo.GetSecondLines(searchCriteria);
SetGridRows(cases);
}
private SecondLineSearchCriteria CreateSearchCriteria() {
return new SecondLineSearchCriteria(
GetSetting().UserInformation.Language,
personalInjury: chPersonalInjury.Checked,
riskForPersonalInjury: chRiskForPersonalInjury.Checked,
compensationDemand: chCompensationDemand.Checked,
secondLine: chSecondLine.Checked,
status: GetSelectedStatus()
);
}
private WorkFlowRowStatus.Type? GetSelectedStatus() {
if(EmptyStatusSelected())
return null;
WorkFlowRowStatus.Type selectedStatus = (WorkFlowRowStatus.Type) Enum.Parse(typeof(WorkFlowRowStatus.Type), ddlStatusSelect.SelectedValue);
return selectedStatus;
}
private bool EmptyStatusSelected() {
int selectedIndex = ddlStatusSelect.SelectedIndex;
return selectedIndex <= 0;
}
private SecondLineTableRow GetRowFromGridItem(GridItem item) {
return new SecondLineTableRow(
GetValueFromColumn<string>(item, "ArticleNumber"),
GetValueFromColumn<string>(item, "ArticleDescription"),
GetValueFromColumn<string>(item, "CaseType"),
GetValueFromColumn<string>(item, "Status"),
GetValueFromColumn<string>(item, "Language"),
GetValueFromColumn<DateTime>(item, "Created"),
GetValueFromColumn<int?>(item, "CaseId")
);
}
private T GetValueFromColumn<T>(GridItem item, string column) {
var itemValue = item.OwnerTableView.DataKeyValues[item.ItemIndex][column];
var x = item.OwnerTableView.DataKeyValues[item.ItemIndex];
return (T) itemValue;
}
private DateTime GetDateTimeFromColumn(GridItem item, string column) {
var itemValueStr = item.OwnerTableView.DataKeyValues[item.ItemIndex][column] as string;
return DateTime.Parse(itemValueStr);
}
}
}
Question
Why are the rows removed when pressing a column header? Why doesn't the sorting work?
Thanks!
The rebind is most likely the issue, though according to telerik examples you should also check that the expression isn't already set.
From the examlple at: https://demos.telerik.com/aspnet-ajax/grid/examples/functionality/sorting/basic-sorting/defaultcs.aspx
protected void RadGrid1_SortCommand(object source, Telerik.Web.UI.GridSortCommandEventArgs e)
{
//Default sort order Descending
if (this.CheckBox1.Checked)
{
if (!e.Item.OwnerTableView.SortExpressions.ContainsExpression(e.SortExpression))
{
GridSortExpression sortExpr = new GridSortExpression();
sortExpr.FieldName = e.SortExpression;
sortExpr.SortOrder = GridSortOrder.Ascending;
e.Item.OwnerTableView.SortExpressions.AddSortExpression(sortExpr);
}
}
}
Rebinding the grid does not seem to be needed and may be what is causing the content to disappear, try removing it.
Actually i am trying to redirect command argument of a button present in a data list to another page. I am using Request.QueryString method to access the command argument on another page with the help of command name of the button. Please help me with it...
this is code of button present inside Data List
<asp:Button ID="Button1" runat="server" Text="Read" CommandArgument='<%# Eval("id")%>' OnClick="Button1_Click" CommandName="content"/>
this is code present in DataList Item command function
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
Response.Redirect("content.aspx?content=" +e.CommandArgument.ToString());
}
this is the onclick function code
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("content.aspx");
}
this is the code on another page(content.aspx)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String id = Request.QueryString["content"];
Label1.Text = id;
}
}
this is entire datalist code
<asp:DataList ID="DataList1" runat="server" DataKeyField="Id" DataSourceID="SqlDataSource1" Height="657px" RepeatColumns="4" RepeatDirection="Horizontal" Width="1248px" OnItemCommand="DataList1_ItemCommand" OnItemDataBound="DataList1_ItemDataBound">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<ItemStyle ForeColor="#000066" />
<ItemTemplate>
<table class="auto-style2">
<tr>
<td style="text-align: center">
<asp:Label ID="Label2" runat="server" Text='<%# Eval("name") %>'></asp:Label>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Id") %>' Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Image ID="Image2" runat="server" Height="250px" ImageUrl='<%# Eval("image") %>' Width="250px" />
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<br />
<asp:ImageButton ID="ImageButton1" runat="server" CommandName="addtofav" CommandArgument='<%# Eval("id")%>' Height="30px" Width="20px" />
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Button ID="Button1" runat="server" Text="Read" CommandArgument='<%# Eval("id")%>' OnClick="Button1_Click" CommandName="content"/>
</td>
</tr>
</table
<br />
<br />
</ItemTemplate>
<SelectedItemStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
it does redirect to another page(content.aspx) but the label does not show the querystring text.
Try updating the DataList1_ItemCommand event to this:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "content")
{
Response.Redirect("content.aspx?content=" +e.CommandArgument.ToString());
}
}
also make sure you are checking IsPostBack in Page_Load method of this page code behind.
Yes i got the desired output. Actually i was also using another button to redirect to a diiferent page in DataList1_ItemCommand function. So i just needed to seperate the Response.redirects of the 2 buttons by putting them in if loop.
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "content")
{
Response.Redirect("content.aspx?content="+e.CommandArgument.ToString());
}
if (e.CommandName == "addtofav")
{
Response.Redirect("sortbyAZ.aspx?addtofav=" + e.CommandArgument.ToString());
}
}
Thanks You everybody for helping me out with this one
I think you are not casting the Request.QueryString["content"] to string format, try this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String id = Request.QueryString["content"];
Label1.Text = id;
}
}
You can find all information you need in this tutorial. from #microsoft msdn
Best of luck
<%# Page Language="C#" AutoEventWireup="True" %>
<%# Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>DataList Select Example</title>
<script runat="server">
ICollection CreateDataSource()
{
// Create sample data for the DataList control.
DataTable dt = new DataTable();
DataRow dr;
// Define the columns of the table.
dt.Columns.Add(new DataColumn("Item", typeof(Int32)));
dt.Columns.Add(new DataColumn("Qty", typeof(Int32)));
dt.Columns.Add(new DataColumn("Price", typeof(double)));
// Populate the table with sample values.
for (int i = 0; i < 9; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i * 2;
dr[2] = 1.23 * (i + 1);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
void Page_Load(Object sender, EventArgs e)
{
// Load sample data only once, when the page is first loaded.
if (!IsPostBack)
{
ItemsList.DataSource = CreateDataSource();
ItemsList.DataBind();
}
}
void Item_Command(Object sender, DataListCommandEventArgs e)
{
// Set the SelectedIndex property to select an item in the DataList.
ItemsList.SelectedIndex = e.Item.ItemIndex;
// Rebind the data source to the DataList to refresh the control.
ItemsList.DataSource = CreateDataSource();
ItemsList.DataBind();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<h3>DataList Select Example</h3>
Click <b>Select</b> to select an item.
<br /><br />
<asp:DataList id="ItemsList"
GridLines="Both"
CellPadding="3"
CellSpacing="0"
OnItemCommand="Item_Command"
runat="server">
<HeaderStyle BackColor="#aaaadd">
</HeaderStyle>
<AlternatingItemStyle BackColor="Gainsboro">
</AlternatingItemStyle>
<SelectedItemStyle BackColor="Yellow">
</SelectedItemStyle>
<HeaderTemplate>
Items
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton id="SelectButton"
Text="Select"
CommandName="Select"
runat="server"/>
Item <%# DataBinder.Eval(Container.DataItem, "Item") %>
</ItemTemplate>
<SelectedItemTemplate>
Item:
<asp:Label id="ItemLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Item") %>'
runat="server"/>
<br />
Quantity:
<asp:Label id="QtyLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Qty") %>'
runat="server"/>
<br />
Price:
<asp:Label id="PriceLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}")
%>'
runat="server"/>
</SelectedItemTemplate>
</asp:DataList>
</form>
</body>
</html>
By the way I think you don't need define Button Click event. Already defined path with variable. Just convert button to Link Button and remove Button Click Event
I am trying to have the clicked on(selected) ListView item be highlighted. However what is currently happening is the last selected item is being highlighted instead.
Here is my asp.net code:
<asp:ListView ID="UsersListView" AutoPostBack="true" runat="server" OnSelectedIndexChanging="UsersListView_SelectedIndexChanging" OnSelectedIndexChanged="UsersListView_SelectedIndexChanged" >
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr>
<td id="itemPlaceholder" runat="server">
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:LinkButton ID="UserNameLinkButton" CommandName="Select" runat="server" Text='<%# Container.DataItem %>'/>
</td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr runat="server" style="background-color: #336699;">
<td>
<asp:LinkButton ID="UserNameLinkButton" CommandName="Select" runat="server" Text='<%# Container.DataItem %>' BackgroundColor="#336699" ForeColor="White" />
</td>
</tr>
</SelectedItemTemplate>
</asp:ListView>
Here is my C# code beside:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
List<string> users = new List<string>()
{
"Gary",
"Joe",
"Brian"
};
UsersListView.DataSource = users;
UsersListView.DataBind();
}
}
protected void UsersListView_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
{
UsersListView.SelectedIndex = e.NewSelectedIndex;
}
protected void UsersListView_SelectedIndexChanged(object sender, EventArgs e)
{
}
Thank you for your help.
You have to use OnCommand for link button or use ListViewItemCommand and pass Item.DisplayIndex as argument to linkButton attribute CommandArgument while you are selecting item and in your case when link button is not to highlight because you are focusing on selecting not over LinkButton.So do your code on Server Side for HighLight Item Button.
Aspx
<asp:ListView ID="UsersListView" AutoPostBack="true" runat="server" OnSelectedIndexChanged="UsersListView_SelectedIndexChanged" OnItemCommand="UsersListView_ItemCommand" OnSelectedIndexChanging="UsersListView_SelectedIndexChanging">
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr>
<td id="itemPlaceholder" runat="server">
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:LinkButton ID="UserNameLinkButton" CommandName="Select" OnCommand="UserNameLinkButton_Command" CommandArgument="<%# Container.DisplayIndex %>" runat="server" Text='<%# Container.DataItem %>'/>
</td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr runat="server">
<td>
<asp:LinkButton ID="UserNameLinkButton" CommandName="Select" CommandArgument="<%# Container.DisplayIndex %>" runat="server" Text='<%# Container.DataItem %>' ForeColor="White" />
</td>
</tr>
</SelectedItemTemplate>
</asp:ListView>
cs(Code)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> users = new List<string>()
{
"Gary",
"Joe",
"Brian"
};
UsersListView.DataSource = users;
UsersListView.DataBind();
}
}
int selectedIndex=0;
protected void UsersListView_ItemCommand(object sender, ListViewCommandEventArgs e)
{
foreach(var item in UsersListView.Items)
{
LinkButton reset=item.FindControl("UserNameLinkButton") as LinkButton;
reset.BackColor = System.Drawing.Color.White;
reset.ForeColor = System.Drawing.Color.Blue;
}
LinkButton linkButton = (e.Item.FindControl("UserNameLinkButton")) as LinkButton;
linkButton.BackColor = System.Drawing.ColorTranslator.FromHtml("#336699");
linkButton.ForeColor = System.Drawing.Color.White;
}
protected void UsersListView_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
{
}
protected void UsersListView_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void UserNameLinkButton_Command(object sender, CommandEventArgs e)
{
//you can also do work here for when one of link button give command.(clicked)
}
Tested
I want to display my gridview details in respective textbox by clicking Edit buttonfield appear in gridview. I am able get only first row(row[0]) data, either by default or by clicking all over the another rows. But I need each row by clicking each row edit button. Here is my design code. I am using VS 2013 and SQL Server 2012.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Admin.aspx.cs" Inherits="RigoTest.Admin" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 50%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<asp:GridView ID="gvdetails" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"
GridLines="None" Width="800px" HorizontalAlign="Center" OnRowEditing="gvdetails_RowEditing" OnRowCommand="gvdetails_RowCommand">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<%--<asp:TemplateField HeaderText="ID" Visible="false">
<EditItemTemplate>
<asp:TextBox ID="txtID" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Question">
<EditItemTemplate>
<asp:TextBox ID="txtQue" runat="server" Text='<%# Bind("question") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblQue" runat="server" Text='<%# Bind("question") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
--%>
<asp:BoundField DataField="ID" HeaderText="ID" Visible="false" />
<asp:BoundField DataField="question" HeaderText="Question" />
<%--<asp:CommandField ShowEditButton="True" HeaderText="Edit2" />--%>
<asp:ButtonField HeaderText="Edit" CommandName="edit" Text="Edit" />
<%--<asp:CommandField CausesValidation="False" HeaderText="Edit2" InsertVisible="False" ShowCancelButton="False" ShowEditButton="True" UpdateText="" />--%>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</center>
</div>
<div style="height: 300px; margin-top: 250px">
<center>
<table width="40%" class="auto-style1">
<tr>
<td>
Add/Edit Question</td>
<td>
</td>
<td> </td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td> </td>
</tr>
<tr>
<td>
<asp:Label ID="Label5" runat="server" Text="Question :"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtquestion" runat="server" Width="295px"></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td>
<asp:Label ID="Label3" runat="server" Text="Option :"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtoption" runat="server" Width="295px"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnadd" runat="server" Text="Add" Width="50px" OnClick="btnadd_Click" />
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:ListBox ID="ListBox1" runat="server" Width="300px"></asp:ListBox>
</td>
<td>
<asp:Button ID="btndelete" runat="server" Text="Delete" Width="50px" OnClick="btndelete_Click" />
<br />
<br />
<asp:Button ID="btnselect" runat="server" Text="Select" Width="50px" OnClick="btnselect_Click" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label4" runat="server" Text="Correct Option :"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtcorrectoption" runat="server" Width="295px"></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td>
<br />
<asp:Button ID="btnsave" runat="server" Text="Save" Width="100px" />
</td>
<td> </td>
<td> </td>
</tr>
</table>
</center>
</div>
</form>
</body>
HERE IS MY ASP.NET CODE
public partial class Admin : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("server = yamma; uid = sa; pwd = /*-; database = rigo");
SqlCommand cmd;
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
public static DataTable dtDefault = new DataTable();
public Int64 n;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
showdata();
//string EditID = Request.QueryString["EditId"];
}
}
public void showdata()
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd = new SqlCommand("RigoSelect", con);
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
da.Fill(dtDefault);
gvdetails.DataSource = dt;
gvdetails.DataBind();
}
protected void btnadd_Click(object sender, EventArgs e)
{
ListBox1.Items.Add(txtoption.Text); //to select data from textbox to listbox
}
protected void btndelete_Click(object sender, EventArgs e)
{
string remove = ListBox1.SelectedItem.Text;
ListBox1.Items.Remove(remove);
////clear all items in listbox
//listBox1.Items.Clear();
}
protected void btnselect_Click(object sender, EventArgs e)
{
txtcorrectoption.Text = ListBox1.SelectedItem.Text;
}
protected void gvdetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
//private Int64 n;
//for(int i=0;i<=n;i++)
//{
int id = int.Parse(gvdetails.Rows[0].Cells[0].Text);
DataRow[] dr = null;
dr = dtDefault.Select("ID = '" + id + "'");
txtquestion.Text = dr[0]["question"].ToString();
txtoption.Text = dr[0]["options"].ToString();
//}
showdata();
}
protected void gvdetails_RowEditing(object sender, GridViewEditEventArgs e)
{
// when boundfied is exist in gridview then id can get....thisway
//int id = int.Parse(gvdetails.Rows[e.NewEditIndex].Cells[0].Text);
////Label lbl = (Label)gvdetails.Rows[e.NewEditIndex].Cells[0].FindControl("lblID");
////string id = lbl.Text.Trim();
////int EID = int.Parse(id);
//// Response.Redirect("Admin.aspx?EditId=" + id + "");
//DataRow[] dr = null;
//dr = dtDefault.Select("ID = '" + id + "'");
//txtquestion.Text = dr[0]["question"].ToString();
//txtoption.Text = dr[0]["options"].ToString();
//showdata();
}
}
}
My problem occurs here
protected void gvdetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
//private Int64 n;
//for(int i=0;i<=n;i++)
//{
int id = int.Parse(gvdetails.Rows[0].Cells[0].Text);
DataRow[] dr = null;
dr = dtDefault.Select("ID = '" + id + "'");
txtquestion.Text = dr[0]["question"].ToString();
txtoption.Text = dr[0]["options"].ToString();
//}
showdata();
}
Here is my main problem occurs:
protected void gvdetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
//private Int64 n;
//for(int i=0;i<=n;i++)
//{
int id = int.Parse(gvdetails.Rows[0].Cells[0].Text);
DataRow[] dr = null;
dr = dtDefault.Select("ID = '" + id + "'");
txtquestion.Text = dr[0]["question"].ToString();
txtoption.Text = dr[0]["options"].ToString();
//}
showdata();
}
When I click on any row that display only first row data. I want to get each row data by each clicking on respective textbox of grid row.
I have tried with commandfield but when try to add the data of option textbox (txtoption) in listbox with add button, it automatically display update, cancel option in gridview.
In the gvdetails_RowCommand event, you're always accessing the first row in the GridView.
int id = int.Parse(gvdetails.Rows[0].Cells[0].Text);
See if this works instead (referencing the currently selected row):
int id = int.Parse(gvdetails.SelectedRow.Cells[0].Text);
Here is a sample code for your reference. Hope this helps.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName =="edit")
{
int i = Convert.ToInt32(e.CommandArgument);
YourTextBox1.Text = GridView1.Rows[i].Cells[0].Text;
YourTextBox2.Text = GridView1.Rows[i].Cells[1].Text;
}
}
I have a scenario as below.
There are 3 check boxes.3 textbox associated with each.Grid gets populated on entering a search value in the textbox.On selecting a row on this grid,I need to hide the grid and selected value(one column) is populated into another textbox.I am getting "Object reference not set to an instance of an object.",when I implementing the logic for hiding the grid.Checkbox checked,value entered in search textbox,grid is populated ,a row selected,second textbox populated with grid value,grid gets hidden--> after this process repeated for 2-3 times,again checking on a check box gives the error.
Please find the markup with above controls.
<table width="500px">
<tr>
<td>
<fieldset id="fssearch" runat="server">
<legend>Search </legend>
<table>
<tr>
<td>
<asp:CheckBox ID="CBFile" runat="server" Text="File No" OnCheckedChanged="CBFile_CheckedChanged"
AutoPostBack="true" />
</td>
<td>
<asp:CheckBox ID="CBname" runat="server" Text="Patient Name" OnCheckedChanged="CBname_CheckedChanged"
AutoPostBack="true" />
</td>
<td>
<asp:CheckBox ID="CBMobile" runat="server" Text="Mobile No" OnCheckedChanged="CBMobile_CheckedChanged"
AutoPostBack="true" />
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="RTFileS" onkeyup="KeyUp();" runat="server" OnTextChanged="RTFileS_TextChanged" Visible="false"></asp:TextBox>
</td>
<td colspan="2">
<asp:TextBox ID="RTNameS" onkeyup="KeyUp();" runat="server" OnTextChanged="RTNameS_TextChanged" Visible="false"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="RTMobileS" onkeyup="KeyUp();" runat="server" OnTextChanged="RTMobileS_TextChanged" Visible="false"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="4">
<telerik:RadGrid ID="gvPatientList" runat="server" AllowFilteringByColumn="True"
AllowPaging="True" GridLines="None" OnSelectedIndexChanged="gvPatientList_SelectedIndexChanged" >
<PagerStyle Mode="NextPrevAndNumeric" AlwaysVisible="true" />
<GroupingSettings CaseSensitive="false" />
<ItemStyle HorizontalAlign="Left" />
<HeaderStyle HorizontalAlign="Left" />
<AlternatingItemStyle HorizontalAlign="Left" />
<ClientSettings EnablePostBackOnRowClick="true">
<Selecting AllowRowSelect="true" />
</ClientSettings>
<MasterTableView AutoGenerateColumns="False" DataKeyNames="pt_regid">
<CommandItemTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</CommandItemTemplate>
<Columns>
<telerik:GridBoundColumn HeaderText="Patient Name" UniqueName="pt_name" DataField="pt_name"
AllowFiltering="false">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn HeaderText="File No" UniqueName="pt_fileno" DataField="pt_fileno"
AllowFiltering="false">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn HeaderText="Mobile" UniqueName="pt_pmobileno" DataField="pt_pmobileno"
AllowFiltering="false">
</telerik:GridBoundColumn>
</Columns>
</MasterTableView>
<HeaderContextMenu EnableImageSprites="True" CssClass="GridContextMenu GridContextMenu_Default">
</HeaderContextMenu>
</telerik:RadGrid>
</td>
</tr>
</table>
</fieldset>
</td>
</tr>
</table>
On selecting a row on the grid,I am populating name column value to a textbox and hiding the grid as below.
protected void gvPatientList_SelectedIndexChanged(object sender, EventArgs e)
{
GridDataItem RegId = gvPatientList.SelectedItems[0] as GridDataItem;
string regid = RegId.GetDataKeyValue("pt_regid").ToString();
foreach (GridDataItem dataItem in gvPatientList.Items)
{
if (dataItem.Selected)
{
RCFName.Text = dataItem["pt_name"].Text;
}
}
gvPatientList.Visible = false;
}
Above mentioned checkboxes act like radio buttons and javascript for the same is as below
<script language="CS" runat="server">
private void makeRadioGroupFromCheckBoxes(IEnumerable<CheckBox> checkBoxes)
{
StringBuilder sb = new StringBuilder();
foreach (CheckBox cb in checkBoxes)
{
foreach (CheckBox innercb in checkBoxes)
{
if (innercb != cb)
{
sb.Append("document.getElementById('");
sb.Append(innercb.ClientID);
sb.Append("').checked = false;");
}
}
cb.Attributes["onclick"] = "if(this.checked){" + sb.ToString() + "}else{this.checked = true;}";
sb = new StringBuilder();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.makeRadioGroupFromCheckBoxes(new CheckBox[] { CBFile, CBname, CBMobile });
}
}
Grid gets populated on textchanged event and 'onkeyup="KeyUp();' function of the textbox,associated with it as below.
aspx:
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
var timer = null;
function KeyUp() {
if (timer != null) {
clearTimeout(timer);
}
timer = setTimeout(LoadTable, 500);
}
function LoadTable() {
$find("<%= RadAjaxManager1.ClientID %>").ajaxRequest("FilterGrid");
}
</script>
</telerik:RadCodeBlock>
code behind:
protected void RadAjaxManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
{
if (e.Argument.IndexOf("FilterGrid") != -1)
{
gvPatientList.Rebind();
}
}
protected void RTFileS_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(RTFileS.Text))
{
_scheduleService = new ScheduleService();
clsSchedule clsschedule = new clsSchedule();
string search = " where OldRegnNo like '" + RTFileS.Text + "%" + "'";
gvPatientList.DataSource = _scheduleService.GetAllPatients(search);
gvPatientList.Rebind();
}
}
On checkedchanged eveent of check boxes,I am making the grid visible.
protected void CBFile_CheckedChanged(object sender, EventArgs e)
{
if (CBFile.Checked)
{
RTFileS.Visible = true;
gvPatientList.Visible = true;
gvPatientList.MasterTableView.Visible = true;
gvPatientList.Rebind();
}
else
{
RTFileS.Visible = false;
}
}
Ajaxmanager is as below:
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" OnAjaxRequest="RadAjaxManager1_AjaxRequest">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="gvPatientList">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="gvPatientList" LoadingPanelID="RadAjaxLoadingPanel1" />
<telerik:AjaxUpdatedControl ControlID="RCFName" />
</UpdatedControls>
</telerik:AjaxSetting>
<telerik:AjaxSetting AjaxControlID="RadAjaxManager1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="gvPatientList" LoadingPanelID="RadAjaxLoadingPanel1" />
</UpdatedControls>
</telerik:AjaxSetting>
I hope hiding/unhiding the grid gives me the error.Please suggest your ideas on this.
Thanks,
Soumya
Please try with below code snippet. You get error because you try to ajaxify grid which was visible false.
protected void Page_PreRender(object sender, EventArgs e)
{
if (gvPatientList.Visible)
{
RadAjaxManager1.AjaxSettings.AddAjaxSetting(gvPatientList, gvPatientList, RadAjaxLoadingPanel1);
RadAjaxManager1.AjaxSettings.AddAjaxSetting(gvPatientList, RCFName);
}
}