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);
}
}
Related
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'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.
Below is code of a GirdView in which i've taken a PagerTemplate which is working fine except the attribute PagerSettings-PageButtonCount="3".
I wanted to display only three page numbers at a time which is normally accomplished by the PageButtonCount attribute.
Asp.Net
<asp:GridView
id="grdMovies"
DataSourceID="srcMovies"
AllowPaging="true"
PageSize="3"
Runat="server"
PagerSettings-PageButtonCount="3"
OnDataBound="grdMovies_DataBound">
<PagerTemplate>
<table>
<tr>
<td>
<asp:LinkButton
id="lnkPrevious"
Text="< Prev"
CommandName="Page"
CommandArgument="Prev"
ToolTip="Previous Page"
Runat="server" />
</td>
<td>
<asp:Menu
id="menuPager"
Orientation="Horizontal"
OnMenuItemClick="menuPager_MenuItemClick"
CssClass="menu"
Runat="server" />
</td>
<td>
<asp:LinkButton
id="lnkNext"
Text="Next >"
CommandName="Page"
CommandArgument="Next"
ToolTip="Next Page"
Runat="server" />
</td>
</tr>
</table>
</PagerTemplate>
</asp:GridView>
C# Code
<script runat="server">
protected void grdMovies_DataBound(object sender, EventArgs e)
{
Menu menuPager = (Menu)grdMovies.BottomPagerRow.FindControl("menuPager");
for (int i = 0; i < grdMovies.PageCount; i++)
{
MenuItem item = new MenuItem();
item.Text = (i + 1).ToString();
item.Value = i.ToString();
if (grdMovies.PageIndex == i)
item.Selected = true;
menuPager.Items.Add(item);
}
}
protected void menuPager_MenuItemClick(object sender, MenuEventArgs e)
{
grdMovies.PageIndex = Int32.Parse(e.Item.Value);
}
</script>
How can i achieve this.
Thanks..
I guess you need to add this property in your gridview
PagerSettings-Mode="NumericFirstLast"
I'm trying to write a code that would update only one record for the data.
I do not need to be able to update every field on the row, only one particular field.
I have page that defines a GridView as following:
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<UpdatePanel>
<ContentTemplate>
<fieldset style="width: 1%">
<legend>Search Customer</legend>
<table>
<tr>
<td>
<asp:DropDownList id="ddlSearchOption"
AutoPostBack="True"
OnSelectedIndexChanged="ddlSearchOption_SelectedIndexChanged"
runat="server">
<asp:ListItem Selected="True" Value="SearchBy"> Search By </asp:ListItem>
<asp:ListItem Value="CustID"> Customer ID </asp:ListItem>
<asp:ListItem Value="CustFirst"> First Name </asp:ListItem>
<asp:ListItem Value="CustLast"> Last Name </asp:ListItem>
<asp:ListItem Value="CustCity"> City </asp:ListItem>
</asp:DropDownList>
</td>
<asp:Panel id="pnlCustSearch" runat="server" >
<td>
<asp:Label id="lblEntry" runat="server" Text="" width="120px"></asp:Label>
</td>
<td>
<asp:TextBox id="txtSearchOptions" runat="server" width="50px">Hello</asp:TextBox>
</td>
<td>
<asp:Button id="btnFind" Text="Search" runat="server" onClick="btnFind_Click"></asp:Button>
</td>
</asp:Panel>
</tr>
</table>
</fieldset>
<div id ="msg">
<asp:Label id="lblMsg" runat="server" Text=""></asp:Label>
</div>
<div id="gridShow">
<asp:GridView ID="GridView1" runat="server" GridLines="None" AutoGenerateColumns="false"
AlternatingRowStyle-BackColor="#EEEEEE" EditRowStyle-BorderColor="Red">
<Columns>
<asp:TemplateField Visible="true" HeaderText="Customer ID">
<ItemTemplate>
<asp:Label runat="server" ID="lblCustID" Text='<%#Eval("CustID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label runat="server" ID="lblFirstName" Text='<%#Eval("CustFirstName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label runat="server" ID="lblLastName" Text='<%#Eval("CustLastName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label runat="server" ID="lblCity" Text='<%#Eval("CustCity") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtEmail" Text='<%#Eval("CustEmail") %>' />
<asp:Button runat="server" ID="btnUpdate" Text="Update" onClick="GridView1_btnUpdate_Click"/>
<asp:RequiredFieldValidator runat="server" ID="rfdCountry" ControlToValidate="txtEmail"
ValidationGroup="var1" ErrorMessage="*" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
</UpdatePanel>
</asp:Content>
Then in codebehind I write the following:
protected void GridView1_btnUpdate_Click(Object sender, EventArgs e)
{
//Code goes here
}
When clicking button to update email nothing happens.
What am I doing wrong?
I tried to use one of suggestions here:
if (!IsPostBack)
{
GridView1.DataSource = App_Data.DataHandler.GetData("fname", "de");
GridView1.DataBind();
GridView1.Visible = true;
}
The data is displayed but the click event does not work anyway
I added the following to my GridView definition:
onrowcommand="GridView1_RowCommand"
and added the code suggested:
<asp:Button runat="server" ID="btnUpdate" Text="Update" CommandName="UpdateEmail"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
In my .cs file I added the following:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateEmail")
{
//Get the index from the argument
int index = Convert.ToInt32(e.CommandArgument);
//Get the row
GridViewRow row = GridView1.Rows[index];
//Do whatever you need with your row here!
}
}
Still, click event does not fire.
Ok, here is my code behind .cs file:
public partial class index : System.Web.UI.Page
{
protected override object LoadPageStateFromPersistenceMedium()
{
return Session["__VIEWSTATE"];
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
Session["VIEWSTATE"] = viewState;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Reset();
else
lblMsg.Text = "";
}
protected void Reset()
{
pnlCustSearch.Visible = false;
GridView1.Visible = false;
lblMsg.Text = "";
}
protected void ddlSearchOption_SelectedIndexChanged(object sender, EventArgs e)
{
Reset();
String ddlSelected = ddlSearchOption.SelectedValue;
if (ddlSelected != "")
{
ViewState["ddlSelected"] = ddlSelected;
pnlCustSearch.Visible = true;
SelectLabel(ddlSelected);
}
}
protected void SelectLabel(String choice)
{
switch (choice)
{
case "CustID":
lblEntry.Text = "Enter Customer ID";
break;
case "CustFirst":
lblEntry.Text = "Enter First Name";
break;
case "CustLast":
lblEntry.Text = "Enter Last Name";
break;
case "CustCity":
lblEntry.Text = "Enter City";
break;
default:
lblEntry.Text = "Enter Customer ID";
break;
}
}
protected void btnFind_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
String option = (String)ViewState["ddlSelected"];
String input = txtSearchOptions.Text.Trim();
GridView1.DataSource = DataHandler.GetData(option,input);
GridView1.DataBind();
GridView1.Visible = true;
}
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateEmail")
{
//Get the index from the argument
int index = Convert.ToInt32(e.CommandArgument);
//Get the row
GridViewRow row = GridView1.Rows[index];
//Do whatever you need with your row here!
}
}
protected void btnUpdate_Click(Object sender, EventArgs e)
{
String txt = null;
txt = "here";
}
}
When you try to handle events from GridView, you need to use a CommandName and a CommandArgument then handle the RowCommand event from the GridView.
See http://msdn.microsoft.com/... for reference.
ASP.Net page should look like :
<asp:ButtonField runat="server" ID="btnUpdate" Text="Update"
CommandName="UpdateEmail"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>" />
In the RowCommand event :
if (e.CommandName == "UpdateEmail")
{
//Get the index from the argument
int index = Convert.ToInt32(e.CommandArgument);
//Get the row
GridViewRow row = GridView1.Rows[index];
//Do whatever you need with your row here!
}
I got it, finally. I had to change <asp:Button/> to
`<asp:ButtonField Text="Update Email" CommandName="UpdateEmail"`
and remove it from ItemTemplate.
But why this was a problem. What I wanted to do is just to display textfield in the same itemtemplate with button?
Actually, the answer was much easier then I thought originally. I just used different values to set session: __VIEWSTATE and VIEWSTATE
protected override object LoadPageStateFromPersistenceMedium()
{
return Session["__VIEWSTATE"];
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
Session["VIEWSTATE"] = viewState;
}
As soon as I changed it, button was able to fire events.
Thank you
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;
}
}