I'm building a social network in asp. I code main page has post status and comment after each status using repeater control, but when I click on 'Post' button and 'Comment' button the repeater control not refresh. I mush logout and login again to display new status and new comment. How can I solve this problem:
MainPage.aspx
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h2>Hello</h2>
<asp:Label ID="lblUser" runat="server" Text=""></asp:Label>
<asp:Label ID="lblID" runat="server" Text=""></asp:Label>
<hr />
<asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="btnPost" runat="server" Text="Post" OnClick="btnPost_Click" />
<hr />
<asp:Repeater ID="repeater" runat="server" OnItemDataBound="repeater_ItemDataBound">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="labelID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Mess_Id") %>'></asp:Label>
<li><%#DataBinder.Eval(Container.DataItem, "Message")%></li>
<asp:Repeater ID="repeatComment" runat="server">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
<ItemTemplate>
<li>
<%#DataBinder.Eval(Container.DataItem, "Comments")%>
</li>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:TextBox ID="txtComment" runat="server"></asp:TextBox>
<asp:Button ID="btnComment" runat="server" Text="Comment" OnClick="btnComment_Click" />
<br />
</ItemTemplate>
</asp:Repeater>
MainPage.aspx.cs
private List<Message> list;
private ESupervisionEntities db;
private MessageController message;
int id;
private System.Web.UI.WebControls.Repeater repeatComment;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["USER_NAME"] != null)
{
lblUser.Text = Session["USER_NAME"].ToString();
lblID.Text = Session["USER_ID"].ToString();
}
if (!IsPostBack)
{
db = new ESupervisionEntities();
message = new MessageController();
id = Int32.Parse(lblID.Text);
list = message.getAllMyByID(db, id, 2);
repeater.DataSource = list;
repeater.DataBind();
}
}
protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if ((item.ItemType == ListItemType.Item) ||
(item.ItemType == ListItemType.AlternatingItem))
{
repeatComment = (Repeater)item.FindControl("repeatComment");
var myLabel = e.Item.FindControl("labelID") as Label;
int num = Int32.Parse(myLabel.Text);
List<MessComment> lst = message.getAllCommentByID(db, id, num);
repeatComment.DataSource = lst;
repeatComment.DataBind();
}
}
protected void btnPost_Click(object sender, EventArgs e)
{
db = new ESupervisionEntities();
message = new MessageController();
id = Int32.Parse(lblID.Text);
message.createMess(db, id, 2, txtMessage.Text, true);
}
protected void btnComment_Click(object sender, EventArgs e) {
var btn = (Button)sender;
var item = (RepeaterItem)btn.NamingContainer;
Button comment = (Button)item.FindControl("btnComment");
TextBox txtComment = (TextBox)item.FindControl("txtComment");
Label msgID = (Label)item.FindControl("labelID");
db = new ESupervisionEntities();
message = new MessageController();
id = Int32.Parse(lblID.Text);
message.createComment(db, int.Parse(msgID.Text), id, 2, txtComment.Text, true);
}
Try this code...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
private void BindData()
{
db = new ESupervisionEntities();
message = new MessageController();
id = Int32.Parse(lblID.Text);
list = message.getAllMyByID(db, id, 2);
repeater.DataSource = list;
repeater.DataBind();
}
protected void btnPost_Click(object sender, EventArgs e)
{
db = new ESupervisionEntities();
message = new MessageController();
id = Int32.Parse(lblID.Text);
message.createMess(db, id, 2, txtMessage.Text, true);
BindData();
}
protected void btnComment_Click(object sender, EventArgs e)
{
var btn = (Button)sender;
var item = (RepeaterItem)btn.NamingContainer;
Button comment = (Button)item.FindControl("btnComment");
TextBox txtComment = (TextBox)item.FindControl("txtComment");
Label msgID = (Label)item.FindControl("labelID");
db = new ESupervisionEntities();
message = new MessageController();
id = Int32.Parse(lblID.Text);
message.createComment(db, int.Parse(msgID.Text), id, 2, txtComment.Text, true);
BindData();
}
Related
In my application I have a radschedular , when creating a new appointment I am opening in advance mode by specifying StartInsertingInAdvancedForm="True"
My code is given below
.aspx
<telerik:RadScheduler RenderMode="Lightweight" runat="server" ID="rs_course_schedule" CustomAttributeNames="Completed"
StartInsertingInAdvancedForm="True" StartEditingInAdvancedForm="True"
FirstDayOfWeek="Monday" LastDayOfWeek="Friday" Reminders-Enabled="true" SelectedView="WeekView"
RowHeight="30px" AppointmentStyleMode="Simple" OnAppointmentDataBound="RadScheduler1_AppointmentDataBound"
OnAppointmentCommand="rs_course_schedule_OnAppointmentCommand"
OnAppointmentCreated="RadScheduler1_AppointmentCreated" OverflowBehavior="Auto" Skin="Web20"
OnAppointmentInsert="rs_course_schedule_OnAppointmentInsert">
<AdvancedForm Modal="true"></AdvancedForm>
<AppointmentTemplate>
<div class="appointmentHeader">
<asp:Panel ID="RecurrencePanel" CssClass="rsAptRecurrence" runat="server" Visible="false">
</asp:Panel>
<asp:Panel ID="RecurrenceExceptionPanel" CssClass="rsAptRecurrenceException" runat="server"
Visible="false">
</asp:Panel>
<asp:Panel ID="ReminderPanel" CssClass="rsAptReminder" runat="server" Visible="false">
</asp:Panel>
<%#Eval("Subject") %>
</div>
<div>
Assigned to: <strong>
<asp:Label ID="UserLabel" runat="server" Text='<%# Container.Appointment.Resources.GetResourceByType("Faculty") == null ? "None" : Container.Appointment.Resources.GetResourceByType("Faculty").Text %>'></asp:Label>
</strong>
<br />
<asp:CheckBox ID="CompletedStatusCheckBox" runat="server" Text="Completed? " TextAlign="Left"
Checked='<%# !String.IsNullOrEmpty(Container.Appointment.Attributes["Completed"]) && Boolean.Parse(Container.Appointment.Attributes["Completed"]) %>'
AutoPostBack="true" OnCheckedChanged="CompletedStatusCheckBox_CheckedChanged"></asp:CheckBox>
</div>
</AppointmentTemplate>
<ResourceStyles>
<telerik:ResourceStyleMapping Type="Faculty" Key="1" BackColor="red"></telerik:ResourceStyleMapping>
<telerik:ResourceStyleMapping Type="Faculty" Key="2" BackColor="Pink"></telerik:ResourceStyleMapping>
<telerik:ResourceStyleMapping Type="Faculty" Key="3" BackColor="OrangeRed"></telerik:ResourceStyleMapping>
</ResourceStyles>
</telerik:RadScheduler>
in code behind
public partial class Schedule : System.Web.UI.UserControl
{
#region Object Instantiation
readonly BEL_LMS _objLms = new BEL_LMS();
readonly BL_LMS _blLms = new BL_LMS();
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateSchedular();
AddTeachers();
SetDate();
}
}
private void AddTeachers()
{
_objLms.ActivityId = Session["activity_id"].ToString();
DataTable dtFaculty = _blLms.AssignedFaculty(_objLms);
ResourceType resources = new ResourceType("Faculty");
if (dtFaculty.Rows.Count > 0)
{
resources.DataSource = dtFaculty;
resources.KeyField = "userid";
resources.TextField = "acct_name";
resources.ForeignKeyField = "UserId";
rs_course_schedule.ResourceTypes.Add(resources);
}
}
private void SetDate()
{
rs_course_schedule.SelectedDate = DateTime.Now;
}
private void PopulateSchedular()
{
_objLms.Flag = "fetch";
_objLms.ActivityId = "11";
DataTable dtTable = _blLms.FetchScheduleForCourse(_objLms);
if (dtTable.Rows.Count > 0)
{
rs_course_schedule.DataKeyField = "ID";
rs_course_schedule.DataStartField = "Start";
rs_course_schedule.DataEndField = "End";
rs_course_schedule.DataSubjectField = "Subject";
rs_course_schedule.DataDescriptionField = "Description";
//rs_course_schedule.DataReminderField = "Reminder";
rs_course_schedule.DataSource = dtTable;
rs_course_schedule.DataBind();
}
}
protected void CompletedStatusCheckBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox CompletedStatusCheckBox = (CheckBox)sender;
//Find the appointment object to directly interact with it
SchedulerAppointmentContainer appContainer = (SchedulerAppointmentContainer)CompletedStatusCheckBox.Parent;
Appointment appointment = appContainer.Appointment;
_objLms.ActivityId = appointment.ID.ToString();
_objLms.Flag = "update";
int affectedRow = _blLms.UpdateCourse(_objLms); // update checkbox data for that particular schedule
rs_course_schedule.Rebind();
}
protected void RadScheduler1_AppointmentDataBound(object sender, SchedulerEventArgs e)
{
if (e.Appointment.Attributes["Completed"] == "True")
{
e.Appointment.BackColor = System.Drawing.Color.Red;
}
}
protected void RadScheduler1_AppointmentCreated(object sender, AppointmentCreatedEventArgs e)
{
}
protected void rs_course_schedule_OnAppointmentInsert(object sender, AppointmentInsertEventArgs e)
{
SchedulerDataSource.InsertParameters["End"].DefaultValue = e.Appointment.End.ToString();
SchedulerDataSource.InsertParameters["Start"].DefaultValue = e.Appointment.Start.ToString();
SchedulerDataSource.InsertParameters["Subject"].DefaultValue = e.Appointment.Start.ToString();
SchedulerDataSource.InsertParameters["Description"].DefaultValue = e.Appointment.Description;
SchedulerDataSource.InsertParameters["CourseID"].DefaultValue = "1";
//SchedulerDataSource.InsertParameters["User"].DefaultVal;
}
protected void rs_course_schedule_OnAppointmentCommand(object sender, AppointmentCommandEventArgs e)
{
string name = e.CommandName;
}
}
}
Now when I am trying to insert a new appointment this form is opening
But in Save and Cancel button click is not occurring..
How I can solve this issue ?
On a RadGrid I can use the CommandItemTemplate to define my own buttons for, in my case, Save and Cancel the edit (like below)
<CommandItemTemplate>
<div style="padding: 5px 5px;">
<asp:LinkButton ID="btnUpdateEdited" runat="server" CommandName="UpdateEdited">Update</asp:LinkButton>
<asp:LinkButton ID="btnCancel" runat="server" CommandName="CancelAll">Cancel editing</asp:LinkButton>
</div>
</CommandItemTemplate>
On the code behind, I set up the ItemCommand.
> protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName.CompareTo("UpdateEdited") == 0)
{
var commandItem = ((GridCommandItem)e.Item);
//Updade code here.
}
}
How can I access the modified row with the modified fields so I can perform an updade?
You should have them in command item and you can access them like this:
GridDataItem item = (GridDataItem)e.Item;
string value = item["ColumnUniqueName"].Text;
Is this what you want ? Just a sample you might need to modify it..
.aspx
<telerik:RadGrid ID="rg" runat="server" AutoGenerateColumns="false"
OnNeedDataSource="rg_NeedDataSource" OnItemCommand="rg_ItemCommand"
MasterTableView-CommandItemDisplay="Top" OnItemDataBound="rg_ItemDataBound">
<MasterTableView EditMode="InPlace">
<CommandItemTemplate>
<div style="padding: 5px 5px;">
<asp:LinkButton ID="btnUpdateEdited" runat="server"
CommandName="UpdateEdited">Update</asp:LinkButton>
<asp:LinkButton ID="btnCancel" runat="server"
CommandName="CancelAll">Cancel editing</asp:LinkButton>
</div>
</CommandItemTemplate>
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Label ID="lbl" runat="server"
Text='<%# Eval("A") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt" runat="server"
Text='<%# Eval("A") %>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" Text="Edit"
CommandName="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate> </EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("A");
dt.Rows.Add("A1");
// Check & Bind
if (dt != null)
{
// Viewstate
ViewState["Data"] = dt;
rg.DataSource = dt;
rg.DataBind();
dt.Dispose();
}
}
}
protected void rg_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
rg.DataSource = ViewState["Data"] as DataTable;
}
protected void rg_ItemCommand(object sender, GridCommandEventArgs e)
{
// Check
if (e.CommandName == "UpdateEdited")
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("A");
// Loop All
foreach (GridEditableItem item in rg.Items)
{
// Find Control
TextBox txt = item.FindControl("txt") as TextBox;
// Check & Add to DataTable
if (txt != null) dt.Rows.Add(txt.Text.Trim());
}
// Check
if (dt != null && dt.Rows.Count > 0)
{
// Set Viewstate
ViewState["Data"] = dt;
// Bind
rg.DataSource = dt;
rg.DataBind();
// Dispose
dt.Dispose();
}
}
else if (e.CommandName == "CancelAll")
{
// Clear Edit Mode
rg.MasterTableView.ClearChildEditItems();
// Rebind
rg.Rebind();
}
}
protected void rg_ItemDataBound(object sender, GridItemEventArgs e)
{
// Check
if (e.Item is GridCommandItem)
{
// Find Control
LinkButton btnUpdateEdited = e.Item.FindControl("btnUpdateEdited") as LinkButton;
LinkButton btnCancel = e.Item.FindControl("btnCancel") as LinkButton;
// Get is Edit Mode ?
if (rg.EditIndexes.Count > 0)
{
if (btnUpdateEdited != null) btnUpdateEdited.Visible = true;
if (btnCancel != null) btnCancel.Visible = true;
}
else
{
if (btnUpdateEdited != null) btnUpdateEdited.Visible = false;
if (btnCancel != null) btnCancel.Visible = false;
}
}
}
i am a complete asp.net noob and the solution could be something very simple.
i have found, read and tried many answers to questions very similar to my question, but nothing works. i hope to find some help here.
this works perfectly with no problem:
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text='<%# (Container.DataItem as Choice).description %>' CommandName="Choice" CommandArgument='<%# (Container.DataItem as Choice).id %>'/>
<br />
</ItemTemplate>
</asp:Repeater>
code behind:
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Choice> choiceList = new List<Choice>();
// ... code to fill the list ...
Repeater1.DataSource = choiceList;
Repeater1.DataBind();
}
}
void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
int idx = int.Parse( e.CommandArgument.ToString() );
// this function is called
}
but if i use ITemplate it doesn't work:
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
</asp:Repeater>
code behind:
public class MyButtonTemplate : System.Web.UI.ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
Button button = new Button();
button.CommandName = "choice";
button.DataBinding += new EventHandler(Button_DataBinding);
container.Controls.Add(button);
container.Controls.Add(new LiteralControl("<br />"));
}
}
static void Button_DataBinding(object sender, System.EventArgs e)
{
Button button = (Button)sender;
RepeaterItem repeaterItem = (RepeaterItem)button.NamingContainer;
button.ID = "button" + (repeaterItem.DataItem as Choice).id.ToString();
button.CommandArgument = (repeaterItem.DataItem as Choice).id.ToString();
button.Text = (repeaterItem.DataItem as Choice).description;
}
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Choice> choiceList = new List<Choice>();
// ... code to fill the list ...
Repeater1.ItemTemplate = new MyButtonTemplate();
Repeater1.DataSource = choiceList;
Repeater1.DataBind();
}
}
void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
int idx = int.Parse( e.CommandArgument.ToString() );
// this function is NOT called
}
the buttons are displayed, but the event is not fired.
i have already tried saving a delegate in MyButtonTemplate and assigning the button click event - it does not work.
thank you!
In the grid I have following columns
<Columns>
<asp:TemplateField HeaderText="select to pay">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" OnCheckedChanged="chkSelect_OnCheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Reference" HeaderText="Invoice" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center">
</asp:BoundField>
<asp:BoundField DataField="ChargedDate" HeaderText="Date of charge" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" DataFormatString="{0:MM-dd-yyyy}">
</asp:BoundField>
<asp:BoundField DataField="Amount" HeaderText="Amount" HeaderStyle- HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
</asp:BoundField>
<asp:TemplateField HeaderText="Amount applied">
<ItemTemplate>
<asp:TextBox ID="txtPayAmount" Width="80px" runat="server" AutoPostBack="true" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
Please tell, In the grid if I chose a check box, the amount value should be displayed in the textbox of the same row. If I checked more than one check boxes the values should displayed in the text boxes of related check boxes/ Rows. the sum should be displayed in the textbox below the grid. What should I need to write under "OnSelect_CheckedChanged" event?
Please try with the below code snippet.
ASPX
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="TotalAmount" ShowFooter="true">
<Columns>
<asp:TemplateField HeaderText="select to pay">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" OnCheckedChanged="chkSelect_OnCheckedChanged"
AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<%# Eval("TotalAmount", "{0:#,##0.00}")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount applied">
<ItemTemplate>
<asp:TextBox ID="txtPayAmount" Width="80px" runat="server" />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox1" Width="80px" runat="server" />
</FooterTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
ASPX.CS
public partial class Forum : System.Web.UI.Page
{
protected void Page_Init(object sender, System.EventArgs e)
{
GridView gv = new GridView();
gv.ID = "GridView1";
gv.AutoGenerateColumns = false;
gv.ShowFooter = true;
gv.DataKeyNames = new string[] { "TotalAmount" };
TemplateField tf = new TemplateField();
tf.ItemTemplate = new MyCustomTemplate();
gv.Columns.Add(tf);
BoundField bf = new BoundField();
bf.DataField = "TotalAmount";
gv.Columns.Add(bf);
tf = new TemplateField();
tf.ItemTemplate = new MyCustomTextTemplate();
tf.FooterTemplate = new MyCustomFooterTextTemplate();
gv.Columns.Add(tf);
this.form1.Controls.Add(gv);
}
protected void Page_Load(object sender, System.EventArgs e)
{
GridView gv = form1.FindControl("GridView1") as GridView;
if (!IsPostBack)
{
dynamic data = new[] {
new { ID = 1, Name = "Name1",TotalAmount= 10},
new { ID = 2, Name = "Name2",TotalAmount= 20},
new { ID = 3, Name = "Name3",TotalAmount= 30},
new { ID = 4, Name = "Name4",TotalAmount= 40},
new { ID = 5, Name = "Name5",TotalAmount= 50}
};
gv.DataSource = data;
gv.DataBind();
}
}
protected void Page_PreRender(object sender, System.EventArgs e)
{
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
dynamic data = new[] {
new { ID = 1, Name ="Name_1"},
new { ID = 2, Name = "Name_2"},
new { ID = 3, Name = "Name_3"},
new { ID = 4, Name = "Name_4"},
new { ID = 5, Name = "Name_5"}
};
}
}
public class MyCustomTemplate : ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
CheckBox cb = new CheckBox();
cb.ID = "chkSelect";
cb.AutoPostBack = true;
cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
container.Controls.Add(cb);
}
protected void cb_CheckedChanged(object sender, EventArgs e)
{
GridViewRow row = (sender as CheckBox).NamingContainer as GridViewRow;
TextBox txtPayAmount = row.FindControl("txtPayAmount") as TextBox;
if ((sender as CheckBox).Checked)
{
txtPayAmount.Text = Convert.ToString((row.Parent.Parent as GridView).DataKeys[row.RowIndex]["TotalAmount"]);
}
else
{
txtPayAmount.Text = string.Empty;
}
int TotalAmount = 0;
foreach (GridViewRow rowv in (row.Parent.Parent as GridView).Rows)
{
CheckBox chk = rowv.FindControl("chkSelect") as CheckBox;
if (chk.Checked)
{
TotalAmount += Convert.ToInt32((row.Parent.Parent as GridView).DataKeys[rowv.RowIndex]["TotalAmount"]);
}
}
GridViewRow rowf = (row.Parent.Parent as GridView).FooterRow;
((TextBox)rowf.FindControl("TextBox1")).Text = TotalAmount.ToString();
}
}
public class MyCustomTextTemplate : ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
TextBox cb = new TextBox();
cb.ID = "txtPayAmount";
container.Controls.Add(cb);
}
}
public class MyCustomFooterTextTemplate : ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
TextBox cb = new TextBox();
cb.ID = "TextBox1";
container.Controls.Add(cb);
}
}
You mean there are rows in the grid with one check box and a text box columns? Each row contain a checkbox and other columns values as mentioned in the code and a Text box? Please attach a image/ screenshot.
I you want to do it using javascript then please try this.
$(function () {
$('input:checkbox').click(function (e) {
calculateSum(5); // sum of 5th column
});
function calculateSum(colidx) {
total = 0.0;
$("tr:has(:checkbox:checked) td:nth-child(" + colidx + ")").each(function () {
var Tot = ($(this).text());
Tot = parseFloat(Tot.replace(/,/g, ''));
total += Tot;
});
$("#<%=txtTotalAmt.ClientID %>").val(total).toFixed(2);
}
});
At OnCheckedChanged event it should be
protected void chkSelect_OnCheckedChanged(object sender, EventArgs e)
{
String czTemp = String.Empty;
GridViewRow gr = (GridViewRow)((CheckBox)sender).Parent.Parent;
GridViewRow footer = grdDues.FooterRow;
TextBox txtAmount = (TextBox)gr.Cells[3].FindControl("txtPayAmount");
TextBox txtAmountPaid = (TextBox)footer.FindControl("txtAmountPaid");
double dbTotalAmt = Convert.ToDouble(txtAmountPaid.Text.Replace("$","").ToString());
if( ((CheckBox)sender).Checked )
{
txtAmount.Enabled = true;
czTemp = grdDues.Rows[gr.RowIndex].Cells[3].Text.ToString();
txtAmount.Text = czTemp.ToString();
dbTotalAmt = dbTotalAmt + Convert.ToDouble(czTemp);
}
else
{
txtAmount.Enabled = false;
czTemp = grdDues.Rows[gr.RowIndex].Cells[3].Text.ToString();
dbTotalAmt = dbTotalAmt - Convert.ToDouble(czTemp);
txtAmount.Text = "0.00";
}
txtAmountPaid.Text = dbTotalAmt.ToString("C");}
I have a GridView that includes BoundField and TemplateField elements. Some of the TemplateField elements are dynamically generated. For the sake of reference, here is the GridView that I am using
<asp:GridView ID="myGridView" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" ShowFooter="True" EnableModelValidation="True"
OnLoad="myGridView_Load" OnRowCommand="myGridView_RowCommand"
OnRowEditing="myGridView_RowEditing" OnRowDeleting="myGridView_RowDeleting"
OnRowCancelingEdit="myGridView_RowCancelingEdit"
OnRowUpdating="myGridView_RowUpdating">
<Columns>
<asp:BoundField DataField="Number" Visible="true" HeaderText="Test" />
<asp:TemplateField HeaderText="Number">
<EditItemTemplate>
<asp:TextBox ID="tb1" runat="server" Text='<%# Bind("Number") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lb1" runat="server" Text='<%# Bind("Number") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftb" runat="server" Text="[x]" />
</FooterTemplate>
</asp:TemplateField>
<%-- Dynamically Generated Columns Will Be Inserted Here --%>
<asp:TemplateField HeaderText="Actions">
<EditItemTemplate>
<asp:LinkButton ID="ulb" runat="server" Text="update" CommandName="Update" />
<asp:LinkButton ID="clb" runat="server" Text="cancel" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="slb" runat="server" Text="insert"
OnClick="saveLinkButton_Click" />
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="elb" runat="server" Text="edit" CommandName="Edit" />
<asp:LinkButton ID="dlb" runat="server" Text="delete" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField
</Columns>
<EmptyDataTemplate>
<table border="0" cellpadding="0" cellspacing="0">
<tr><td>Number</td></tr>
<tr>
<td><asp:TextBox ID="ntb" runat="server" /></td>
<td><asp:LinkButton ID="slb2" runat="server" Text="save" OnClick="saveLinkButton_Click" /></td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>
When the GridView initially loads, everything is loaded properly. However, anytime I perform a command (edit, insert, delete), all of the data goes away. Oddly, the BoundField values still appear correctly. However, any TemplateField does not seem to get rendered. The code that I am using to work with this GridView is here:
public partial class GridView : System.Web.UI.Page
{
private List<string> dynamicColumnNames = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
LoadPageData();
}
protected void saveLinkButton_Click(object sender, EventArgs e)
{
}
protected void myGridView_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
BindGridData();
}
}
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{ }
protected void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
myGridView.EditIndex = e.NewEditIndex;
BindGridData();
}
protected void myGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
LoadPageData();
BindGridData();
}
protected void myGridView_RowCancelingEdit(object sender, EventArgs e)
{
myGridView.EditIndex = -1;
BindGridData();
}
protected void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
myGridView.EditIndex = -1;
LoadPageData();
BindGridData();
}
private void BindGridData()
{
// Create a temporary data source
DataTable tempData = new DataTable();
tempData.Columns.Add("ID");
tempData.Columns.Add("Number");
// Dynamically add template columns
foreach (string columnName in dynamicColumnNames)
{
tempData.Columns.Add(columnName);
TemplateField templateField = new TemplateField();
templateField.HeaderTemplate = new MyTemplateField(ListItemType.Header, columnName);
templateField.ItemTemplate = new MyTemplateField(ListItemType.Item, columnName);
templateField.EditItemTemplate = new MyTemplateField(ListItemType.EditItem, columnName);
templateField.FooterTemplate = new MyTemplateField(ListItemType.Footer, columnName);
myGridView.Columns.Insert(2, templateField);
}
// Add some phony data
Random random = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < 10; i++)
{
DataRow tempRow = tempData.NewRow();
tempRow["Number"] = (i + 1);
foreach (string column in dynamicColumnNames)
tempRow[column] = random.NextDouble();
tempData.Rows.Add(tempRow);
}
// Bind the data to the grid
myGridView.DataSource = tempData;
myGridView.DataBind();
}
private void LoadPageData()
{
dynamicColumnNames.Add("USA");
dynamicColumnNames.Add("Japan");
dynamicColumnNames.Add("Mexico");
}
}
internal class MyTemplateField : ITemplate
{
// The type of the list item
private ListItemType listItemType;
// The value to use during instantiation
private string value1 = string.Empty;
public MyTemplateField(ListItemType listItemType, string value1)
{
this.listItemType = listItemType;
this.value1 = value1;
}
public void InstantiateIn(Control container)
{
if (listItemType == ListItemType.Item)
{
TextBox textBox = new TextBox();
textBox.ReadOnly = true;
textBox.DataBinding += new EventHandler(textBox_DataBinding);
container.Controls.Add(textBox);
}
else if (listItemType == ListItemType.EditItem)
{
TextBox textBox = new TextBox();
textBox.DataBinding += new EventHandler(textBox_DataBinding);
container.Controls.Add(textBox);
}
else if (listItemType == ListItemType.Header)
{
Literal literal = new Literal();
literal.Text = value1;
container.Controls.Add(literal);
}
else if (listItemType == ListItemType.Footer)
{
TextBox textBox = new TextBox();
container.Controls.Add(textBox);
}
}
private void textBox_DataBinding(object sender, EventArgs e)
{
TextBox textBox = (TextBox)(sender);
GridViewRow row = (GridViewRow)(textBox.NamingContainer);
textBox.Text = DataBinder.Eval(row.DataItem, value1).ToString();
}
}
How do I use commands in a GridView with Dynamically added columns? What is wrong with my code?
Thank you!
Dynamically added controls must be added on each post, you can't just add these controls on the first page load. Try removing your BindGridData() from within the Page.IsPostBack == false.