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>
Related
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 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;
}
}
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 have two dropdown lists in asp.net which are generated from a database. When the user selected a value from the first dropdown list, the second dropdown list will be generated based on this value.
I also have a gridview with has a add row, delete and save function. Within each cell of the gridview are textboxes which are self generated by the add row function.
What I want to do is to have a add selected value button from the dropdown list and for the value of the second dropdown list to be added into the first cell of the gridview.
However, if there are muliple gridview rows generated, then a option should appear asking which row the value should be inserted into.
Please can I get some help on this?
Below is the ASP.net
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="workout">
<div class="exerciseDD">
<fieldset class="exercise">
<legend>Exercise List</legend>
<div style="text-align: justify">
To begin choose the exercise number you wish to add an exercise too. Then use
the dropdown menu to select the exercise you wish to use in your workout.
Finally click add to insert the exercise into the workout.
<br />
<br />
<asp:Label ID="Label3" runat="server" CssClass="bold"
Text="Choose an exercise number:"></asp:Label>
<br />
<asp:DropDownList ID="ExerNo" runat="server">
<asp:ListItem Selected="True">1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:Label ID="MuscleGDD" runat="server" CssClass="bold" Text="Muscle Group:"></asp:Label>
<br />
<asp:DropDownList ID="MuscleDD" runat="server" AutoPostBack="True"
Height="22px" onselectedindexchanged="MuscleDD_SelectedIndexChanged"
Width="100%">
</asp:DropDownList>
<br />
<br />
<asp:Label ID="Label4" runat="server" CssClass="bold" Text="Exercise Name:"></asp:Label>
<br />
<asp:DropDownList ID="ExerciseDD" runat="server" AutoPostBack="True"
Height="22px" onselectedindexchanged="ExerciseDD_SelectedIndexChanged"
Width="100%">
</asp:DropDownList>
<br />
<br />
<asp:Button ID="Add" runat="server" Text="Add Exercise" onclick="Add_Click" />
<br />
<asp:Label ID="Label5" runat="server" CssClass="bold"
Text="Exercise Description:"></asp:Label>
<br />
<asp:Label ID="Exerdes" runat="server"></asp:Label>
</div>
</fieldset>
</div>
<div class="createWO">
<fieldset class="create">
<legend>Create Workout</legend>
<asp:Label ID="LabelUserId" runat="server" Visible="True"></asp:Label>
<br />
<strong>Workout Name:</strong> <asp:TextBox ID="WorkName" runat="server"></asp:TextBox>
<div>
<asp:Label ID="CurrentDate" runat="server" />
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDeleting="grvWorkout_RowDeleting">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:BoundField DataField="Userid" HeaderText="User ID" Visible="false"/>
<asp:TemplateField HeaderText="Exercise Name">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Set">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Repetition">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemTemplate>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row"
onclick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:gridview>
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
<br />
<br />
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Below is the Code behind. The code contains the add row, delete and save function. The code also contains the functionality to populate the dropdown lists:
private void SetInitialRow()
{
//Sets the initial row of the gridview
}
private void AddNewRowToGrid()
{
//Adds a new row and placing any data back into the gridview
}
private void SetPreviousData()
{
//temp save of the dat
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable MuscleG = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Muscle_id], [MuscleName] FROM [MuscleGroup]", con);
adapter.Fill(MuscleG);
MuscleDD.DataSource = MuscleG;
MuscleDD.DataTextField = "MuscleName";
MuscleDD.DataValueField = "Muscle_id";
MuscleDD.DataBind();
}
//MuscleDD.Items.Insert(0, new ListItem("Select Muscle Name", "0"));
}
if (!Page.IsPostBack)
{
SetInitialRow();
}
CurrentDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
}
protected void MuscleDD_SelectedIndexChanged(object sender, EventArgs e)
{
int muscleid = Convert.ToInt32(MuscleDD.SelectedValue);
DataTable exercises = new DataTable();
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Exercise_id], [ExerciseName] FROM [Exercise] WHERE [Muscle_id] = " + muscleid, con2);
adapter.Fill(exercises);
ExerciseDD.DataSource = exercises;
ExerciseDD.DataTextField = "ExerciseName";
ExerciseDD.DataValueField = "Exercise_id";
ExerciseDD.DataBind();
}
//ExerciseDD.Items.Insert(0, new ListItem("Select Exercise", "0"));
}
protected void ExerciseDD_SelectedIndexChanged(object sender, EventArgs e)
{
int exerciseid = Convert.ToInt32(ExerciseDD.SelectedValue);
using (SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
{
con3.Open();
string cmdStr = "SELECT [Exercise_id], [ExerDesc] FROM [ExerciseDescription] WHERE [Exercise_id] = '" + exerciseid +"'";
SqlCommand Des = new SqlCommand(cmdStr, con3);
SqlDataReader reader = Des.ExecuteReader();
reader.Read();
Exerdes.Text = reader["ExerDesc"].ToString();
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void Button1_Click(object sender, EventArgs e)
{
//Saves data in gridview to database
}
//A method that returns a string which calls the connection string from the web.config
private string GetConnectionString()
{
}
//A method that Inserts the records to the database
private void InsertRecords(StringCollection sc)
{
//Inserts the records into the database
}
protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
}
private void SetRowData()
{
//Set data in temp table
}
protected void grvWorkout_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//Deletes the row
}
//This function relates to the button I wish to insert the value of the dropdown menu into the gridview.
protected void Add_Click(object sender, EventArgs e)
{
//Add dropdown value
}
Here is a quick & dirty sample I made based on your requirement to get you started.
You can select a car make & get selected models
You can add rows to the gridview on button click
You can select the stock model's properties on checkbox click of gridview
Aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="gridTest.aspx.cs" Inherits="WebApplication1.Gridview" %>
<!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Make:
<asp:DropDownList ID="ddlMake" runat="server" AppendDataBoundItems="True" AutoPostBack="True"
OnSelectedIndexChanged="ddlMake_SelectedIndexChanged">
<asp:ListItem Text=" - Select -" Value=""></asp:ListItem>
</asp:DropDownList>
<br />
Model:
<asp:DropDownList ID="ddlModels" runat="server">
</asp:DropDownList>
<br />
<br />
<h2>
Accessories
<asp:Button ID="btnAddConsignment" runat="server" OnClick="btnAddConsignment_Click"
Text="Add Consignment" />
</h2>
<asp:GridView ID="gvItems" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Consignment No.">
<ItemTemplate>
<%# Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Color">
<itemtemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</itemtemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tires">
<itemtemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</itemtemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NOS">
<itemtemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</itemtemplate>
</asp:TemplateField>
<asp:TemplateField>
<itemtemplate><asp:CheckBox ID="cbSameAsStock" runat="server" AutoPostBack="True"
oncheckedchanged="cbSameAsStock_CheckedChanged" Text="Same as stock?" /></itemtemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Codebehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace WebApplication1
{
public partial class Gridview : System.Web.UI.Page
{
public class Make
{
public int Id { get; set; }
public string Name { get; set; }
public List<Make> GetMake()
{
return new List<Make>()
{
new Make { Id = 1, Name = "Ford" },
new Make { Id = 2, Name = "BMW" },
new Make { Id = 3, Name = "Lamborghini" }
}.ToList();
}
}
public class Models
{
public int ModelId { get; set; }
public int MakeId { get; set; }
public string Name { get; set; }
public List<Models> GetModels()
{
return new List<Models>()
{
new Models { ModelId=1, MakeId=1, Name="Ford Truck 1"},
new Models { ModelId=2, MakeId=1, Name="Ford Truck 2"},
new Models { ModelId=3, MakeId=1, Name="Ford Truck 3"},
new Models { ModelId=4, MakeId=3, Name="Gollarado"},
new Models { ModelId=5, MakeId=3, Name="Murcillago"}
};
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Temporary data fetched through a list. In production you will fetch data from the database
Make make = new Make();
ddlMake.DataSource = make.GetMake();
ddlMake.DataTextField = "Name";
ddlMake.DataValueField = "Id";
ddlMake.DataBind();
if(ViewState["dt"]!=null)
{
DataTable dt = ViewState["dt"] as DataTable;
gvItems.DataSource = dt;
}
}
}
protected void ddlMake_SelectedIndexChanged(object sender, EventArgs e)
{
// Filter second dropdown list
Models model = new Models();
ddlModels.DataSource = model.GetModels().Where(s => s.MakeId == int.Parse(ddlMake.SelectedValue));
ddlModels.DataTextField = "Name";
ddlModels.DataValueField = "ModelId";
ddlModels.DataBind();
}
protected void btnAddConsignment_Click(object sender, EventArgs e)
{
// Bind gridview to temporary data & store inside viewstate
DataTable dt = null;
if (ViewState["dt"] == null)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(int)));
dt.Columns.Add(new DataColumn("Color", typeof(string)));
dt.Columns.Add(new DataColumn("Tires", typeof(string)));
dt.Columns.Add(new DataColumn("NOS", typeof(string)));
dt.Columns["Id"].AutoIncrement = true;
dt.Columns["Id"].AutoIncrementSeed = 1;
}
else
dt = ViewState["dt"] as DataTable;
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
gvItems.DataSource = dt;
gvItems.DataBind();
ViewState["dt"] = dt;
}
protected void cbSameAsStock_CheckedChanged(object sender, EventArgs e)
{
// Get your checkbox from gridview's selected row
CheckBox cbTemp = sender as CheckBox;
if (cbTemp != null)
{
// If selected, append selected model name to textboxes
if (cbTemp.Checked)
{
var selectedModel = ddlModels.SelectedItem.Text; // your selected car model
GridViewRow gr = ((CheckBox) sender).NamingContainer as GridViewRow;
if (gr != null)
{
TextBox txt1 = gr.FindControl("TextBox1") as TextBox;
TextBox txt2 = gr.FindControl("TextBox2") as TextBox;
TextBox txt3 = gr.FindControl("TextBox3") as TextBox;
txt1.Text = "Same as stock "+ selectedModel;
txt2.Text = "Same as stock " + selectedModel;
txt3.Text = "Same as stock " + selectedModel;
}
}
}
}
}
}
I have trying to Edit and Update my GridView in bulk.
I have generated a CheckBox in the first column of my GridView. It works something like this:
If I check a particular row in the GridView, the row gets editable.
Like this I can check as many rows I want to edit the GridView.
I have given a universal button called UPDATE, once after editing all the rows, and click on this button, the GridView is updated looping in each row checking for CheckBox.Check.
The issue I am facing here is that, when I click on any CheckBox in the GridView row, I am not getting TextBox.
I am trying to convert Label to TextBox on checking a CheckBox in the GridView.
So when I check a row, the text corresponding to Label template for that cell goes invisible according to my program, but fails to get the TextBox with the value of that cell.
The code I have tried is this:
protected void OnCheckedChanged(object sender, EventArgs e)
{
bool isUpdateVisible = false;
CheckBox chk = (sender as CheckBox);
if (chk.ID == "chkAll")
{
foreach (GridViewRow row in GridView3.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked = chk.Checked;
}
}
}
CheckBox chkAll = (GridView3.HeaderRow.FindControl("chkAll") as CheckBox);
chkAll.Checked = true;
foreach (GridViewRow row in GridView3.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
for (int i = 3; i < row.Cells.Count; i++)
{
row.Cells[i].Controls.OfType<Label>().FirstOrDefault().Visible = !isChecked;
if (row.Cells[i].Controls.OfType<TextBox>().ToList().Count > 0)//this condition is not satisfying when I debug the program. what is wrong in this line?
{
row.Cells[i].Controls.OfType<TextBox>().FirstOrDefault().Visible = isChecked;
}
if (isChecked && !isUpdateVisible)
{
isUpdateVisible = true;
}
if (!isChecked)
{
chkAll.Checked = false;
}
}
}
}
UpdateGrid.Visible = isUpdateVisible;
}
The aspx code is:
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False"
DataKeyNames="Location_Profile_Name">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location_Profile_Name" SortExpression="Location_Profile_Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Location_Profile_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Home_Profile" SortExpression="Label10">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Home_Profile") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Home_Profile") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns></asp:GridView>
I have commented the issue I am facing in the program above. Kindly help.
I see that you are mixing to approaches, the Template approach (ItemTemplate, EditTemplate), and some Code-Behind approach (doing things hard-coded in code behind).
For your cenario, i sugest do it in code-behind, to get full control of the situation.
i addapted your code to explain my sugestion. Here is:
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location_Profile_Name" SortExpression="Location_Profile_Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Location_Profile_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Home_Profile" SortExpression="Label10">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Home_Profile") %>'></asp:Label>
<%--Here are the controls that edit this row, we will handle this on code-behind--%>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Home_Profile") %>' Visible="false"></asp:TextBox>
<asp:Button ID="btnSave" Text="save" runat="server" Visible="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The "EditTemplate" was deleted, YOU will handle your own edit template.
protected void OnCheckedChanged(object sender, EventArgs e)
{
//... Your code ...
// Here we find the controls tha we will handle
CheckBox chkAll = (GridView3.HeaderRow.FindControl("chkAll") as CheckBox);
chkAll.Checked = true;
foreach (GridViewRow row in GridView3.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckBox1 = (CheckBox)row.FindControl("CheckBox1");
Label Label2 = (Label)row.FindControl("Label2");
TextBox TextBox1 = (TextBox)row.FindControl("TextBox1");
Button btnSave = (Button)row.FindControl("btnSave");
//GridView3.SetEditRow(row.RowIndex);
if (CheckBox1 != null)
{
if (CheckBox1.Checked)
{
if (TextBox1 != null && Label2 != null)
{
// Shows your "Edit Template"
btnSave.Visible = true;
Label2.Visible = false;
TextBox1.Visible = true;
TextBox1.Text = Label2.Text;
}
}
}
}
}
}
for now, you have the control of situation :)
see this post Edit Update Delete Multiple Records
basically you need to add in your gridview
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server"
AutoPostBack="true"
OnCheckedChanged="chkSelect_CheckedChanged"/>
</ItemTemplate>
and code behind:
protected void chkSelect_CheckedChanged
(object sender, EventArgs e)
{
CheckBox chkTest = (CheckBox)sender;
GridViewRow grdRow = (GridViewRow)chkTest.NamingContainer;
TextBox txtname = (TextBox)grdRow.FindControl("txtName");
if (chkTest.Checked)
{
txtname.ReadOnly = false;
}
else
{
txtname.ReadOnly = true;
}
}
if you familiar with Jquery you can easily enable the fields also in client side
Since AutoGenerateEditButton = false, therefore there should be no for Home_Profile. The TextBox template for Home_Profile should be written within and the visibility should be set to false.
The aspx code is:
<asp:TemplateField HeaderText="Home_Profile" SortExpression="Label10">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Home_Profile") %>'></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Home_Profile") %>' Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
i don't have the code for the way i previously did it, here is a little example using similar logic that what you did, i hope it helps
here is an working example doing it the way you did it
Code Behind
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
for (int i = 0; i < 10; i++)
{
DataRow dr = dt.NewRow();
dr[0] = "Test " + i;
dt.Rows.Add(dr);
}
rptITem.DataSource = dt;
rptITem.DataBind();
}
}
protected void UpdateCB(object sender, EventArgs e)
{
foreach (RepeaterItem Item in rptITem.Items)
{
CheckBox cb = (CheckBox)Item.FindControl("cbTest");
TextBox tb = (TextBox)Item.FindControl("tbTest");
Label lb = (Label)Item.FindControl("lbTest");
tb.Visible = cb.Checked;
lb.Visible = !cb.Checked;
}
}
protected void UpdateAll(object sender, EventArgs e)
{
foreach (RepeaterItem Item in rptITem.Items)
{
CheckBox cb = (CheckBox)Item.FindControl("cbTest");
TextBox tb = (TextBox)Item.FindControl("tbTest");
Label lb = (Label)Item.FindControl("lbTest");
cb.Checked = true;
tb.Visible = true;
lb.Visible = false;
}
} }
Aspx Code
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:Repeater ID="rptITem" runat="server">
<HeaderTemplate>
<div style="border:1px solid black">
<div style="width:50px; float:left"><asp:CheckBox ID="cbAll" runat="server" AutoPostBack="true" OnCheckedChanged="UpdateAll" /></div>
<div style="width:200px; float:left;">Name</div>
<div style="clear:both"></div>
</div>
</HeaderTemplate>
<ItemTemplate>
<div style="width:50px; float:left"><asp:CheckBox ID="cbTest" runat="server" AutoPostBack="true" OnCheckedChanged="UpdateCB" /></div>
<div style="width:200px; float:left;"><asp:Label ID="lbTest" runat="server" Text='<%# Eval("Name") %>' ></asp:Label></div>
<div style="width:200px; float:left;"><asp:TextBox ID="tbTest" runat="server" Text='<%# Eval("Name") %>' Visible="false"></asp:TextBox></div>
</ItemTemplate>
<SeparatorTemplate>
<div style="clear:both"></div>
</SeparatorTemplate>
</asp:Repeater>
</asp:Content>