I have a Web form user control and I want to add a calender to a textbox in edit form, but I get this error for txtStudentDOB in void Calendar1_SelectionChanged1(object sender, EventArgs e) . the problem is I cannot access to calender from the edit form context.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
namespace LearningSystem.Controls
{
public partial class usrStudent : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Calendar1.Visible = false;
}
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (Calendar1.Visible == false)
{
Calendar1.Visible = true;
}
else
{
Calendar1.Visible = true;
}
}
void Calendar1_SelectionChanged1(object sender, EventArgs e)
{
txtStudentDOB.Text = Calendar1.SelectedDate.ToShortDateString();
Calendar1.Visible = false;
}
}
here is HTML codes
<asp:FormView ID="frmStudent" runat="server" DataSourceID="odsStudent" Width="100%" OnItemDeleted="frmStudent_ItemDeleted" DataKeyNames="StudentID" OnItemInserted="frmStudent_ItemInserted" OnItemUpdated="frmStudent_ItemUpdated" >
<EditItemTemplate>
<asp:TextBox ID="txtStudentDOB" runat="server" CssClass="form-control" Text='<%# Bind("StudentDOB" , "{0:d}") %>' />
<asp:ImageButton ID="ImageButton1" runat="server" OnClick="ImageButton1_Click" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator12" runat="server" Display="Dynamic" ControlToValidate="txtStudentDOB" ErrorMessage="Please Enter Date of Birth" ForeColor="Red">*</asp:RequiredFieldValidator>
<asp:RangeValidator ID ="rvDate" runat ="server" C
</div>
</div>
<div class="col-md-offset-2 col-md-10"">
<asp:LinkButton ID="btnUpdate" runat="server" CssClass="btn btn-success" CausesValidation="True" CommandName="Update" Text="Update" OnClick="btnUpdate_Click" />
<asp:LinkButton ID="btnCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" Font-Bold="false" />
</div>
</div>
</EditItemTemplate>
<asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_SelectionChanged1" > </asp:Calendar>
You cannot access the control within a formview directly. You need to find it in the form view. Try the following code
void Calendar1_SelectionChanged1(object sender, EventArgs e)
{
TextBox txtStudentDOB = frmStudent.FindControl("txtStudentDOB") as TextBox;
if(txtStudentDOB != null)
{
txtStudentDOB.Text = Calendar1.SelectedDate.ToShortDateString();
Calendar1.Visible = false;
}
}
Related
Below is the markup page:
<%# Page Title="" Language="C#" MasterPageFile="~/Master/MainPage.master" EnableViewState="true" AutoEventWireup="true" CodeBehind="edit.aspx.cs" Inherits="Website.View.edit" %>
...
<asp:Repeater runat="server" ID="rptSample">
<ItemTemplate>
<asp:HyperLink runat="server" ID="refLink" href='http://www.sample.com' Text='Test data' />
<asp:CheckBox runat="server" ID="chkbxDelete" Text="Delete" />
</ItemTemplate>
<SeparatorTemplate>
<br />
</SeparatorTemplate>
</asp:Repeater>
Here's how I bind data on code behind:
protected void Page_Load(object sender, EventArgs e)
{
rptSample.DataSource = getData();
rptSample.DataBind();
}
I've also tried this one:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
rptSample.DataSource = getData();
rptSample.DataBind();
}
}
And tried to get the data on btnSave_Click function
protected void btn_save_Click(object sender, EventArgs e)
{
foreach(RepeaterItem item in rptSample.Items)
{
CheckBox chkbx = (CheckBox) item.FindControl("chkbxDelete");
if (chkbx.Checked)
{
//Do something
}
}
}
If I didn't add the !IsPostBack, the rptSample.Items will be empty but if I remove it, the checkbox will always be false.
What's the problem??
Edit:
As per a user requested, here's the full page load function:
protected void Page_Load(object sender, EventArgs e)
{
bindData();
}
protected void bindData()
{
List<sp_SelectAttachments_Result> attachments = DAL.SelectAttachmentsByID(Request["ID"]);
if (attachments.Count == 0)
divAttachments.Visible = false;
else
{
divAttachments.Visible = true;
rptAttachments.DataSource = attachments;
rptAttachments.DataBind();
}
}
Here's the markup page for divAttachments and rptAttachments
<div runat="server" id="divAttachments" visible="false">
<asp:Repeater runat="server" ID="rptAttachments">
<ItemTemplate>
<asp:HiddenField Value='<%# Eval("ID") %>' runat="server" ID="hidID" />
<asp:HyperLink runat="server" ID="refLink" href='<%# $"/Utils/getFile.ashx?ID={ID}" %>' Text='<%# ((sp_SelectAttachments_Result)Container.DataItem).FileName %>' />
<asp:CheckBox runat="server" ID="chkbxDeleteAttachment" Text="Delete" />
</ItemTemplate>
<SeparatorTemplate>
<br />
</SeparatorTemplate>
</asp:Repeater>
</div>
I suspect that there is something in your code which clears the check boxes or resets the data source of the repeater control.
I suggest creating a clean page and using the code below(which I've tested and it works).Once you have it working slowly start adding any additional logic to the page until you figure out what's causing the problem:
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rptSample.DataSource = getData();
rptSample.DataBind();
}
}
private List<string> getData()
{
return new List<string> { "1", "2", "3" };
}
protected void btn_save_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in rptSample.Items)
{
CheckBox chkbx = (CheckBox)item.FindControl("chkbxDelete");
if (chkbx.Checked)
{
System.Diagnostics.Debugger.Break();
}
}
}
.ASPX:
<form id="form1" runat="server">
<asp:Repeater runat="server" ID="rptSample">
<ItemTemplate>
<asp:HyperLink runat="server" ID="refLink" href='http://www.sample.com' Text='Test data' />
<asp:CheckBox runat="server" ID="chkbxDelete" Text="Delete" />
</ItemTemplate>
<SeparatorTemplate>
<br />
</SeparatorTemplate>
</asp:Repeater>
<asp:Button ID="btn_save" runat="server" Text="Save" OnClick="btn_save_Click" />
</form>
Use Viewstate to hold data. bind viewstate to repeater on load and also use the !IsPostBack for rptSample.DataBind();
I am trying to implement my login and logout through my webpage. There are two panels which toggle. On my page load, the logout panel is made invisible so that the user may only see the login link. After logging in the login panel is made invisible and the logout panel is made visible where the logout link is there for logging out. but the logout linkbutton is not even firing the click event. This is what i see in the browser window at the bottom when i try to click the logout link button
This is my aspx page-
<div>
<asp:Panel ID="LoginPanel" runat="server">
<ul class="style1">
<li>Username</li>
<li><asp:TextBox ID="LoginEmail" runat="server" Width="90%" placeholder="Email" class="form-control"></asp:TextBox></li>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Email Required" ControlToValidate="LoginEmail" ForeColor="#CC0000" Font-Italic="True"></asp:RequiredFieldValidator>
<li>Password</li>
<li><asp:TextBox ID="LoginPassword" runat="server" Width="90%" placeholder="Password" class="form-control" TextMode="Password"></asp:TextBox></li>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Password Required" ControlToValidate="LoginPassword" ForeColor="#CC0000" Font-Italic="True"></asp:RequiredFieldValidator>
<li><asp:Button ID="LoginButton" runat="server" Text="Login" class="btn btn-default" onclick="LoginButton_Click"/>
New User?<asp:HyperLink ID="new_user" runat="server" NavigateUrl="Registration.aspx">Register Here</asp:HyperLink></li>
</ul>
</asp:Panel>
<asp:Panel ID="LogoutPanel" runat="server">
<asp:LinkButton ID="LogoutLink" runat="server" Text="Logout"
onclick="LogoutLink_Click" />
</asp:Panel>
</div>
This is my cs code-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class UserMasterPage : System.Web.UI.MasterPage
{
ConnectionClass cl;
SqlDataReader dr;
string sql;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LogoutPanel.Visible = false;
cl = new ConnectionClass();
}
}
protected void LoginButton_Click(object sender, EventArgs e)
{
sql = "select Id, Email_, Password_, Block from MemberLogin where Email_='" + LoginEmail.Text + "'";
cl = new ConnectionClass();
cl.establishConnection();
cl.createReaderCommand(sql);
dr = cl.executeReaderCommand();
if (dr.HasRows)
{
if (LoginPassword.Text == dr["Password_"].ToString())
{
if (dr["Block"].ToString() == "False")
{
Session["user"] = dr[0].ToString();
LoginPanel.Visible = false;
LogoutPanel.Visible = true;
//Response.Write("login successful");
}
}
}
cl.closeConnection();
}
protected void LogoutLink_Click(object sender, EventArgs e)
{
Session.Abandon();
Response.Redirect("AdminLogin.aspx");
}
}
This is on my master page. I need to solve this problem very soon. Please help me with this.Thanks in advance.
The __DoPostBackWithOptions call associated with the LinkButton is related to the presence of the validators in your page. Setting CausesValidation to false would replace it by the "regular" __doPostBack:
<asp:LinkButton ID="LogoutLink" runat="server" CausesValidation="false" ... />
The validators shown in your markup being in a Panel with Visible = false, they should not be active. But since I don't see anything else that could prevent the postback, turning off the validation for the LinkButton would at least eliminate that possible cause.
By the way, if you have many controls and validators in your form, you may consider grouping them with validation groups. That would allow each button (or other controls causing a postback) to trigger only the relevant validators:
<asp:TextBox ID="txt1a" runat="server" ValidationGroup="Group1" />
<asp:RequiredFieldValidator ID="rfv1a" runat="server" ControlToValidate="txt1a" ValidationGroup="Group1" Text="*" ForeColor="Red" />
<asp:TextBox ID="txt1b" runat="server" ValidationGroup="Group1" />
<asp:RequiredFieldValidator ID="rfv1b" runat="server" ControlToValidate="txt1b" ValidationGroup="Group1" Text="*" ForeColor="Red" />
<asp:Button ID="btn1" runat="server" Text="Button1" ValidationGroup="Group1" />
<br />
<asp:TextBox ID="txt2a" runat="server" ValidationGroup="Group2" />
<asp:RequiredFieldValidator ID="rfv2a" runat="server" ControlToValidate="txt2a" ValidationGroup="Group2" Text="*" ForeColor="Red" />
<asp:TextBox ID="txt2b" runat="server" ValidationGroup="Group2" />
<asp:RequiredFieldValidator ID="rfv2b" runat="server" ControlToValidate="txt2b" ValidationGroup="Group2" Text="*" ForeColor="Red" />
<asp:Button ID="btn2" runat="server" Text="Button2" ValidationGroup="Group2" />
In the example above, a click on btn1 would cause a postback even if txt2a is empty, because they don't belong to the Group1 validation group.
There is a RadGrid inside which there is a RadComboBox and asp Button in
EditItemTemplate.
Below is the current code:
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="240" DropDownWidth="310"
EnableLoadOnDemand="True" OnItemsRequested="ddlAccountCode_ItemsRequested" EnableItemCaching="true"
ShowMoreResultsBox="True" EnableVirtualScrolling="true" AllowCustomText="true" MarkFirstMatch="true"
Filter="Contains" HighlightTemplatedItems="true" CausesValidation="true" AppendDataBoundItems="true"
DataTextField="AccountDescription" DataValueField="AccountCodeID"
ShowDropDownOnTextboxClick="false"
OnClientDropDownOpening="OnClientDropDownOpening" OnClientItemsRequested="OnClientItemsRequested"
OnClientTextChange="LoadECnEntityKeys" />
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClient="btnSearch_Click" />
<asp:Label ID="lblMsg" runat="server" Visible="false"></asp:Label>
</EditItemTemplate>
</telerik:GridTemplateColumn>
protected void btnSearch_Click(object sender, EventArgs e)
{
Response.Write("Default.aspx");
//other code
}
When I type/key-in something inside RadComboBox and click on asp Button,
then only the searching related to key-in text starts and display after execution of OnClick event of asp Button.
Now, the new requirement came to place RadButton(with - Single Click
approach) in place of asp Button, to avoid double click.
Problem is: when I implement RadButton inside EditItemTemplate of RadGrid, RadButton never postback i.e., when I click on it nothing happens.
But same RadButton when I use outside of RadGrid, is working fine.
Below is the code using RadButton(with - Single Click
approach):
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="240" DropDownWidth="310"
EnableLoadOnDemand="True" OnItemsRequested="ddlAccountCode_ItemsRequested" EnableItemCaching="true"
ShowMoreResultsBox="True" EnableVirtualScrolling="true" AllowCustomText="true" MarkFirstMatch="true"
Filter="Contains" HighlightTemplatedItems="true" CausesValidation="true" AppendDataBoundItems="true"
DataTextField="AccountDescription" DataValueField="AccountCodeID"
ShowDropDownOnTextboxClick="false"
OnClientDropDownOpening="OnClientDropDownOpening" OnClientItemsRequested="OnClientItemsRequested"
OnClientTextChange="LoadECnEntityKeys" />
<telerik:RadButton runat="server" ID="btnSearch" Text="Search" SingleClick="true"
SingleClickText="Submitting..." OnClick="btnSearch_Click" />
<asp:Label ID="lblMsg" runat="server" Visible="false"></asp:Label>
</EditItemTemplate>
</telerik:GridTemplateColumn>
protected void btnSearch_Click(object sender, EventArgs e)
{
Response.Write("Default.aspx");
//other code
}
Please let me know why is this hapenning?
Please do reply
Thanks in advance
I would recommend you to use CommandName as button event. Anyway here is my code... I tried use OnClick and CommandName it work perfectly fine. I suspect your error will be some sort of javascript...
.aspx
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" Width="100%"
OnNeedDataSource="RadGrid1_NeedDataSource" OnItemCommand="RadGrid1_ItemCommand"
OnItemDataBound="RadGrid1_ItemDataBound">
<MasterTableView EditMode="InPlace">
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("T")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox ID="rcb" runat="server" AllowCustomText="true">
</telerik:RadComboBox>
<telerik:RadButton runat="server" ID="btnSearch" Text="Search"
SingleClick="true" SingleClickText="Submitting..." CommandName="Search" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<telerik:RadButton ID="btnEdit" runat="server"
Text="Edit" CommandName="Edit"></telerik:RadButton>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadButton ID="btnCancel" runat="server" Text="Cancel"
CommandName="Cancel"></telerik:RadButton>
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("T");
// Loop & Add
for (int i = 0; i < 10; i++)
dt.Rows.Add(i + "");
// Check & Bind
if (dt != null)
{
ViewState["Grid"] = dt;
RadGrid1.DataSource = dt;
RadGrid1.DataBind();
// Dispose
dt.Dispose();
}
}
}
protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = ViewState["Grid"] as DataTable;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
Response.Write("GG");
}
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
// Check
if (e.CommandName == "Search")
{
// Variable
GridEditableItem item = e.Item as GridEditableItem;
string something = "";
// Find Control
RadComboBox rcb = item.FindControl("rcb") as RadComboBox;
// Check
if (rcb != null)
{
// Set
something = rcb.Text;
// Do Something
Response.Write(something);
}
}
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
// Check
if (e.Item is GridEditableItem)
{
// FindControl
RadComboBox rcb = e.Item.FindControl("rcb") as RadComboBox;
// Check
if (rcb != null)
{
rcb.DataSource = ViewState["Grid"] as DataTable;
rcb.DataTextField = "T";
rcb.DataValueField = "T";
rcb.DataBind();
}
}
}
I am working on asp.net web application using c# visual studio 2012. I have created textboxes and labels on runtime and on button click I want to fetch the value inputted by user at run time in the textboxes. But as soon as I click on the button I get error Object reference not set to an instance of an object.
I am new to asp.net. Kindly Help
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="AddEntity.aspx.cs" Inherits="GraphWebApplication.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head>
<body>
<form id="form1" runat="server">
<asp:Table ID="Table1" runat="server" Width="396px" HorizontalAlign="Center">
<asp:TableRow HorizontalAlign="Left">
<asp:TableCell>
<asp:Label ID="Label1" runat="server" Text="Entity Name" Width="193px"></asp:Label>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="TextBox1" runat="server" Width="193px"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow HorizontalAlign="Left">
<asp:TableCell>
<asp:Label ID="Label2" runat="server" Text="No. of Attributes" Width="193px"></asp:Label>
</asp:TableCell>
<asp:TableCell>
<asp:DropDownList ID="DropDownList1" runat="server" Height="22px" Width="197px" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="Select" Value="0" Selected="True"></asp:ListItem>
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
<asp:ListItem Text="4" Value="4"></asp:ListItem>
<asp:ListItem Text="5" Value="5"></asp:ListItem>
<asp:ListItem Text="6" Value="6"></asp:ListItem>
<asp:ListItem Text="7" Value="7"></asp:ListItem>
<asp:ListItem Text="8" Value="8"></asp:ListItem>
<asp:ListItem Text="9" Value="9"></asp:ListItem>
<asp:ListItem Text="10" Value="10"></asp:ListItem>
</asp:DropDownList>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
<br />
<div align="center"><asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<br />
<br />
</div>
<asp:Table ID="Table2" runat="server" HorizontalAlign="Center" Width="396px">
<asp:TableRow>
<asp:TableCell Width="193px">
<asp:Button ID="Button1" runat="server" Text="Add More Entity" Width="163px" OnClick="Button1_Click" />
</asp:TableCell>
<asp:TableCell Width="193px">
<asp:Button ID="Button2" runat="server" Text="Next Step:Add Relationship" Width="170px" OnClick="Button2_Click"/>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
<asp:Label ID="Label3" runat="server"></asp:Label>
<br />
</form>
</body>
</html>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Data.SqlClient;
namespace GraphWebApplication
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int a = Convert.ToInt16(DropDownList1.SelectedValue);
for (int i = 0; i < a; i++)
{
Label labels = new Label();
labels.Text = "AttributeName" + (i + 1).ToString();
TextBox textBoxes = new TextBox();
textBoxes.ID = "TextBoxAttributeName" + (i + 1).ToString();
PlaceHolder1.Controls.Add(labels);
PlaceHolder1.Controls.Add(new LiteralControl(" "));
PlaceHolder1.Controls.Add(textBoxes);
PlaceHolder1.Controls.Add(new LiteralControl("<BR>"));
}
DropDownList1.Enabled = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
int a = Convert.ToInt16(DropDownList1.SelectedValue);
for (int i = 0; i < a; i++)
{
TextBox tt = (TextBox)PlaceHolder1.FindControl("TextBoxAttributeName1");
Response.Write(tt.Text);
//Response.Redirect("~/WebForm1.aspx");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "AddRelationship", "<script>AddRelationship();</script>");
//Response.Redirect("~/WebForm2.aspx");
}
}
}
You can save your current number of attributes into Session and in the OnInit method you can add the Controls (Label+Textbox) to the Placeholder. OnInit gets called before Page_Load. The eventhandlers get called after Page_Load. So in the Button1_Click method the controls are already added to the Placeholder (because the OnInit method added them) and .FindControl will find the controls.
Because you are new to asp.net forms, another thing for better understanding. You maybe wondering: How can the values I've entered into the textboxes still be in the textboxes after you hit the "Add more entity" button? NEW textboxes will be added in the OnInit method, so how can the have the .Text property properly set? This is because of the ViewState. The ViewState will be loaded after the OnInit method and will fill your form elements with their former values.
Also, if you will do this with Session always be careful. (for example: delete the session variables when you don't need them anymore, ...)
Here is my new code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
private int AttributesCount
{
get
{
int ret = 0;
if (Session["AttributesCount"] != null && int.TryParse(Session["AttributesCount"].ToString(), out ret))
{
;
}
return ret;
}
set
{
Session["AttributesCount"] = value;
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
RenderTextboxes();
}
private void RenderTextboxes()
{
for (int i = 0; i < AttributesCount; i++)
{
Label labels = new Label();
labels.Text = "AttributeName" + (i + 1).ToString();
TextBox textBoxes = new TextBox();
textBoxes.ID = "TextBoxAttributeName" + (i + 1).ToString();
PlaceHolder1.Controls.Add(labels);
PlaceHolder1.Controls.Add(new LiteralControl(" "));
PlaceHolder1.Controls.Add(textBoxes);
PlaceHolder1.Controls.Add(new LiteralControl("<BR>"));
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int a = Convert.ToInt16(DropDownList1.SelectedValue);
AttributesCount = a;
RenderTextboxes();
DropDownList1.Enabled = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < AttributesCount; i++)
{
TextBox tt = (TextBox)PlaceHolder1.FindControl("TextBoxAttributeName" + (i + 1));
Response.Write(tt.Text);
//Response.Redirect("~/WebForm1.aspx");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "AddRelationship", "<script>AddRelationship();</script>");
//Response.Redirect("~/WebForm2.aspx");
}
}
}
I've got a databound grid view within a UpdatePanel.
There are textboxes in the template fields which are dynamically created with a for loop.
I have a textChange event associated with each textbox, but the event isn't being fired.
Please help me with it.
Here's the ASP code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<table width="100%">
<%--table for the grid view of buttons--%>
<tr>
<td align="center">
<asp:GridView ID="gvJV" runat="server" AutoGenerateColumns="False"
Height="100%" Width="749px" >
<Columns>
<asp:TemplateField HeaderText="Account">
<ItemTemplate>
<ajaxToolkit:ComboBox ID="AccountId" runat="server" AutoPostBack="false">
</ajaxToolkit:ComboBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="AccountId"
Display="Dynamic" ErrorMessage="Select Account" ForeColor="Red" InitialValue="-1">*</asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnSelect" runat="server" ImageUrl="~/images/icons/edit.png" AutoPostBack="false"
ImageAlign="AbsMiddle" OnClientClick='hdCallerRowID.value = this.parentElement.parentElement.rowIndex-1;' />
<ajaxToolkit:ModalPopupExtender ID="gv_ModalPopupExtender" runat="server" TargetControlID="btnSelect"
PopupControlID="pnlSelectCOA" CancelControlID="btnCancel" BackgroundCssClass="modalBackground">
</ajaxToolkit:ModalPopupExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Memo">
<ItemTemplate>
<asp:TextBox ID="txtMemo" runat="server" BorderStyle="None" AutoPostBack="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Debit">
<ItemTemplate>
<asp:TextBox ID="txtDebit" runat="server" AutoPostBack="false" OnTextChanged="txtDebit_textChanged" comm></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Credit">
<ItemTemplate>
<asp:TextBox ID="txtCredit" AutoPostBack="false" EnableViewState="true" runat="server" OnTextChanged="txtDebit_textChanged"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</asp:UpdatePanel>
and here's the code at back end
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ERP.Controller;
using System.Data;
using AjaxControlToolkit;
using MERP.WebUI.Code;
using ERP.Properties;
namespace MERP.WebUI.Account.GL
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtCalendar_CalendarExtender.SelectedDate = DateTime.Now.Date;
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = new DataTable();
dt.Columns.Add("Dummy");
for (int i = 0; i < 10; i++)
dt.Rows.Add("");
dt.AcceptChanges();
gvJV.DataSource = dt;
gvJV.DataBind();
}
private void SaveForm()
{
int debitTotal = 0;
int creditTotal = 0;
foreach (GridViewRow gvRow in gvJV.Rows)
{
TextBox txtDebit = (TextBox)gvRow.FindControl("txtDebit");
if (txtDebit.Text != string.Empty)
debitTotal += Convert.ToInt32(txtDebit.Text.Trim());
TextBox txtCredit = (TextBox)gvRow.FindControl("txtCredit");
if (txtCredit.Text != string.Empty)
creditTotal += Convert.ToInt32(txtCredit.Text.Trim());
}
if (debitTotal != creditTotal)
((Authenticated)Master).SetMessage("NOT EQUAL");
else
((Authenticated)Master).SetMessage("done successfully");
}
protected void gvJV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ComboBox AccountId = (ComboBox)e.Row.FindControl("AccountId");
Common.BindAccounts(AccountId);
TextBox txtMemo = (TextBox)e.Row.FindControl("txtMemo");
}
}
protected void txtDebit_textChanged(object sender, EventArgs e)
{
GridViewRow row = ((GridViewRow)((TextBox)sender).NamingContainer);
//NamingContainer return the container that the control sits in
TextBox other = (TextBox)row.FindControl("txtCredit");
other.Text = "";
}
protected void btnCancel_Click(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
SaveForm();
}
}
}
I had the same problem. I resolved it by setting the AutoPostBack of the TextBox to true. Therefore the code should be:
<ItemTemplate>
<asp:TextBox ID="txtMemo" runat="server" AutoPostBack="true"></asp:TextBox>
</ItemTemplate>