disable textbox in edit mode - c#

i have a edit function in my gridview. however what i want to do is to disable the visibility of the textbox when i click on update function on a specific data bound. here is my aspx code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="ProductName">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ProductName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ProductName") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="Invalid" ForeColor="Red" ControlToValidate="txtboxProductName"
ValidationExpression="^[a-zA-Z ]+$"></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductDescription">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("ProductDescription") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtboxProductDescription" runat="server" Text='<%# Bind("ProductDescription") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="Invalid"
ForeColor="Red" ControlToValidate="txtboxProductDescription"
ValidationExpression="^[a-zA-Z ]+$"></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:ImageField HeaderText ="ProductImage" DataImageUrlField="ProductImage" SortExpression="ProductImage" ControlStyle-Width ="10">
<ControlStyle Width="50px"></ControlStyle>
</asp:ImageField>
<asp:TemplateField HeaderText="ProductQuantity">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("ProductQuantity") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtboxProductQuant" runat="server" Text='<%# Bind("ProductQuantity") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ErrorMessage="Invalid" ControlToValidate="txtboxProductQuant"
ForeColor="Red" ValidationExpression=^[0-9]*$></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductPrice">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("ProductPrice") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtboxProductPrice" runat="server" Text='<%# Bind("ProductPrice") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator4" runat="server" ErrorMessage="Invalid" ControlToValidate="txtboxProductPrice"
ForeColor="Red" ValidationExpression=^[0-9]*$></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
<%--<asp:CommandField ShowDeleteButton="true" />--%>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkdel" runat="server" Text="Delete" CommandName="Delete"
OnClientClick="return confirm('Confirm Delete?');"></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
and here is my update code behind:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Finding the controls from Gridview for the row which is going to update
//Label id = GridView1.Rows[e.RowIndex].FindControl("lbl_ID") as Label;
int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox ProductName = GridView1.Rows[e.RowIndex].FindControl("txtboxProductName") as TextBox;
TextBox ProductDescription = GridView1.Rows[e.RowIndex].FindControl("txtboxProductDescription") as TextBox;
TextBox ProductQuantity = GridView1.Rows[e.RowIndex].FindControl("txtboxProductQuant") as TextBox;
TextBox ProductPrice = GridView1.Rows[e.RowIndex].FindControl("txtboxProductPrice") as TextBox;
conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=Authorship;Integrated Security =True");
conn.Open();
//updating the record
SqlCommand cmd = new SqlCommand("Update Products set ProductName='" + ProductName.Text + "',ProductDescription='" + ProductDescription.Text + "',ProductQuantity='" + ProductQuantity.Text + "', ProductPrice='" + ProductPrice.Text + "' where ProductID='" + userid + "'", conn);
cmd.ExecuteNonQuery();
conn.Close();
//Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
GridView1.EditIndex = -1;
//Call ShowData method for displaying updated data
gvbind();
}
i don't have the product image inside a edit template and also, product image is not included in my code behind. cant understand why a text box becomes visible on product image when i click on update function. please help.

If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
for example
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Handles GridView1.RowDataBound
If e.Row.RowState = DataControlRowState.Edit Then
ctype(e.Row.Cells(1).Controls(0),TextBox).Enabled=False
End If
End Sub

Related

Insert Grid View column value into Textbox and dropdown on button control

I want to Fill gridview column value into given control
something like Project Title value fill inside project Title text box Problem ID fill inside Selected Problem Dropdown and so on... on button click even
i have taken as control name
Project title as txtProjectTitle,
selectProblem Id as ddlSelectProblem,
Project_Start_Date as txtProjectStartDate,
Project_Target_Date as TextBox1,
gridview as GrdTemp,
Procedd button as Button2_Click
ASPX CODE:
[![<asp:GridView ID="GrdTemp" runat="server" Style="width: 100%; text-align: center" class="table table-striped table-bordered" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="S.No." HeaderStyle-Width="5%">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" Visible="false">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("ID") %>' ID="lblID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project Title">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("Project_Title") %>' ID="lblID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Problem ID">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("Problem") %>' ID="lblID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project Start Date">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("Project_Start_Date") %>' ID="lblID</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project Target Date">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("Project_Target_Date") %>' ID="lblID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns> </asp:GridView>][2]][2]
C# code:
protected void Button2_Click(object sender, EventArgs e)
{
GridViewRow row = (sender as Label).NamingContainer as GridViewRow;
TextBox txtProject = row.FindControl("txtProjectTitle") as TextBox;
txtProject.Text = Convert.ToString((row.Parent.Parent as GridView).DataKeys[row.RowIndex]["Project_Title"]);
DropDownList ddlProblem = row.FindControl("ddlSelectProblem") as DropDownList;
ddlSelectProblem.SelectedItem.Text = Convert.ToString((row.Parent.Parent as GridView).DataKeys[row.RowIndex]["Problem"]);
txtProjectStartDate.Text = Convert.ToString((row.Parent.Parent as GridView).DataKeys[row.RowIndex]["Project_Start_Date"]);
TextBox1.Text = Convert.ToString((row.Parent.Parent as GridView).DataKeys[row.RowIndex]["Project_Target_Date"]);
}

Get text box value from grid view Header

I have grid with text box for filter data on header.I have button outside the grid.I am using this gridview for filtering the grid by some columns. When I click on button I want to get value from text box and dropdownlist on codebehind.cs, below is my webform.aspx code of gridview,
<asp:Button ID="btngetLocationDate" runat="server" Text="Get Filtered Data" OnClick="getTextBoxValue"></asp:Button>
<asp:GridView ID="TrackerGrid" runat="server" BackColor="#CCCCCC" AllowPaging="True" AutoGenerateColumns="false">
<AlternatingRowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<Columns>
<asp:TemplateField HeaderText="User ID" SortExpression="User ID">
<ItemTemplate>
<asp:Label ID="lbluserid" runat="server" Text='<%# Eval("User ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer Name">
<HeaderTemplate>
Full Name:
<asp:DropDownList ID="ddlfullName" runat="server" AutoPostBack="true" OnSelectedIndexChanged="onselectDropdown">
<asp:ListItem Text="ALL" Value="ALL" Selected="True"></asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%# Eval("Full Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile Number">
<HeaderTemplate>
Mobile Number:
<asp:TextBox ID="txtMobilenumber" runat="server" AutoPostBack="true"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblmobile" runat="server" Text='<%# Eval("Mobile Phone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email Address">
<HeaderTemplate>
Email Id:
<asp:TextBox ID="txtemail" runat="server" AutoPostBack="true"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblemail" runat="server" Text='<%# Eval("Email ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Longitude">
<HeaderTemplate>
<asp:Label ID="lbllng" runat="server" Text="Longitude"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbllongi" runat="server" Text='<%# Eval("Longitude") %>' Width="70"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lattitude">
<HeaderTemplate>
<asp:Label ID="lbllat" runat="server" Text="Lattitude"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbllatti" runat="server" Text='<%# Eval("Lattitude") %>' Width="70"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Activated On">
<HeaderTemplate>
<asp:Label ID="lbldevices" runat="server" Text="Activated On"></asp:Label></br>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbldevice" runat="server" Text='<%# Eval("Activated On") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location DateTime" SortExpression="Location DateTime">
<HeaderTemplate>
<asp:Label ID="Label1" runat="server" Text="Location DateTime"></asp:Label></br>
<asp:Label ID="lblStartDate" runat="server" AssociatedControlID="txtStartDate" Text="Start Date"></asp:Label>
<asp:TextBox ID="txtStartDate" runat="server"></asp:TextBox>
<cc1:calendarextender id="CalendarStartDate" runat="server" format="dd/MM/yyyy" targetcontrolid="txtStartDate" popupbuttonid="imgPopup1"></cc1:calendarextender>
<asp:ImageButton ID="imgPopup1" runat="server" ImageUrl="https://cdn4.iconfinder.com/data/icons/small-n-flat/24/calendar-alt-512.png" Height="20px" Width="30px" />
</br>
<asp:Label ID="lblEndDate" runat="server" Text="End Date" AssociatedControlID="txtEndDate"></asp:Label>
<asp:TextBox ID="txtEndDate" runat="server"></asp:TextBox>
<cc1:calendarextender id="CalendarEndDate" runat="server" format="dd/MM/yyyy" targetcontrolid="txtEndDate" popupbuttonid="imgPopup2"></cc1:calendarextender>
<asp:ImageButton ID="imgPopup2" runat="server" ImageUrl="https://cdn4.iconfinder.com/data/icons/small-n-flat/24/calendar-alt-512.png" Height="20px" Width="30px" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblDatetime" runat="server" Text='<%# Eval("Location DateTime") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and I am getting texbox value in codebehind code.
protected void getTextBoxValue(object sender, EventArgs e)
{
DropDownList ddlfullname = (TrackerGrid.HeaderRow.FindControl("ddlfullName") as DropDownList);
string selectedValue = ddlfullname.SelectedItem.Text;
TextBox mobilenumber = (TrackerGrid.HeaderRow.FindControl("txtMobilenumber") as TextBox);
string mobile = mobilenumber.Text;
TextBox email = TrackerGrid.HeaderRow.FindControl("txtemail") as TextBox;
string emailid = email.Text;
TextBox staloc = TrackerGrid.HeaderRow.FindControl("txtStartDate") as TextBox;
string startlocatdate = staloc.Text;
TextBox endloc = TrackerGrid.HeaderRow.FindControl("txtEndDate") as TextBox;
string endlocadate = endloc.Text;
}
I am getting empty value when I debugging this code.I think my code is correct but how i am not getting value of textboxes, i don't understand. Please help me for solving my issue.
Thanks in advance.
You probably did not wrap the DataBind() of the Gridview inside an IspostBack check. If you do not then the values will be rested by the DataBind instead of being saved with ViewState.
protected void Page_Load(object sender, EventArgs e)
{
//not here
TrackerGrid.DataSource = source;
TrackerGrid.DataBind();
if (IsPostBack == false)
{
//but inside an ispostback check
TrackerGrid.DataSource = source;
TrackerGrid.DataBind();
}
}

Input string was not in a correct format in grid view

While binding the gridview i want to get cell control value but in my code throwing an error.Like below i am binding the gridview with edit,delete,and footer rows.
<asp:GridView ID="GridView1" runat="server" Width = "100%"
OnDataBound = "OnDataBound" OnRowCreated = "OnRowCreated"
AutoGenerateColumns = "False" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" AllowSorting="True" AllowPaging ="True" ShowFooter = "True"
OnPageIndexChanging = "OnPaging" onrowediting="EditCustomer"
onrowupdating="UpdateCustomer" onrowcancelingedit="CancelEdit" PageSize = "30">
<Columns>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText="S.NO">
<ItemTemplate><%#Container.DataItemIndex + 1%>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Item Code">
<FooterTemplate>
<asp:Label ID="lblAddItemCode" runat="server"
Text='<%# Eval("ItemId")%>'></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblViewItemCode" runat="server"
Text='<%# Eval("ItemId")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditItemCode" runat="server"
Text='<%# Eval("ItemId")%>'></asp:Label>
</EditItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Item Name">
<EditItemTemplate>
<asp:Label ID="lblEditItemName" runat="server"
Text='<%# Eval("ItemName")%>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlItemNameGrid" runat="server"
DataSourceID="SqlDataSource1" DataTextField="ItemName"
DataValueField="ItemId">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:crmConnectionString3 %>"
SelectCommand="SELECT [ItemId], [ItemName] FROM [ItemMaster] WHERE ([Company_Id] = #Company_Id)">
<SelectParameters>
<asp:SessionParameter DefaultValue="1014" Name="Company_Id"
SessionField="RegistrationId" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblViewItemName" runat="server"
Text='<%# Eval("ItemName")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Unit">
<ItemTemplate>
<asp:Label ID="lblViewUnit" runat="server"
Text='<%# Eval("Unit")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditUnit" runat="server" Text='<%# Eval("Unit")%>' ValidationGroup="EditValidations"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtEditUnit" CssClass="Validators" Display="Dynamic" ControlToValidate="txtEditUnit" runat="server"
ErrorMessage="Unit is required." ForeColor="Red" ValidationGroup="EditValidations"></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddUnit" runat="server" ValidationGroup="AddValidations"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtAddUnit" CssClass="Validators" Display="Dynamic" ControlToValidate="txtAddUnit" runat="server"
ErrorMessage="Unit is required." ForeColor="Red" ValidationGroup="AddValidations"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Quantity">
<ItemTemplate>
<asp:Label ID="lblViewQuantity" runat="server"
Text='<%# Eval("Quantity")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditQuantity" runat="server"
Text='<%# Eval("Quantity")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddQuantity" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtAddQuantity" CssClass="Validators" Display="Dynamic" ControlToValidate="txtAddQuantity" runat="server"
ErrorMessage="Quantity is required." ForeColor="Red" ValidationGroup="AddValidations"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Rate">
<ItemTemplate>
<asp:Label ID="lblViewRate" runat="server"
Text='<%# Eval("Rate")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditRate" runat="server" Text='<%# Eval("Rate")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtEditRate" CssClass="Validators" Display="Dynamic" ControlToValidate="txtEditRate" runat="server"
ErrorMessage="Quantity is required." ForeColor="Red" ValidationGroup="EditValidations"></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddRate" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtAddRate" CssClass="Validators" Display="Dynamic" ControlToValidate="txtAddRate" runat="server"
ErrorMessage="Rate is required." ForeColor="Red" ValidationGroup="AddValidations"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Total">
<ItemTemplate>
<asp:Label ID="lblViewTotal" runat="server"
Text='<%# Eval("Total")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditTotal" runat="server" Text='<%# Eval("Total")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtEditTotal" CssClass="Validators" Display="Dynamic" ControlToValidate="txtEditTotal" runat="server"
ErrorMessage="Total is required." ForeColor="Red" ValidationGroup="EditValidations"></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddTotal" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtAddTotal" CssClass="Validators" Display="Dynamic" ControlToValidate="txtAddTotal" runat="server"
ErrorMessage="Total is required." ForeColor="Red" ValidationGroup="AddValidations"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="80px" HeaderText="Add Item">
<ItemTemplate>
<%--<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:LinkButton ID="lnkB" runat="Server" Text="Delete" CommandName="ItemDelete"></asp:LinkButton>
</span>--%>
<%--<asp:LinkButton ID="lnkRemove" runat="server" OnClick="lnkRemove_Click">Delete</asp:LinkButton>--%>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument='<%#Eval("ItemDetailId")%>' Text="Delete" OnClientClick = "return confirm('Do you want to delete?')"
onclick="DeleteRecord"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add" ValidationGroup="AddValidations"
OnClick = "InsertItemDetails" />
</FooterTemplate>
<ItemStyle Width="80px" />
</asp:TemplateField>
<%--<asp:CommandField ShowDeleteButton="True" ButtonType="Button" HeaderText="Delete Item" />--%>
<asp:CommandField ShowEditButton="True" ValidationGroup="EditValidations" HeaderText="Edit Item" />
</Columns>
</asp:GridView>
below i am retrieving 'Total' coloumn's label control value.
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
subTotal = 0;
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
int itemId = Convert.ToInt32(dt.Rows[e.Row.RowIndex]["ItemId"]);
total += Convert.ToDouble(dt.Rows[e.Row.RowIndex]["Total"]);
if (itemId != currentId)
{
if (e.Row.RowIndex > 0)
{
for (int i = subTotalRowIndex; i < e.Row.RowIndex; i++)
{
Label lblViewTotal = ((Label)e.Row.Cells[6].FindControl("lblViewTotal")) as Label;
if (lblViewTotal != null && lblViewTotal.Text != string.Empty) //Check whether it is null or not
{
subTotal += Convert.ToDouble(lblViewTotal.Text);
}
}
this.AddTotalRow("Sub Total", subTotal.ToString("N7"));
subTotalRowIndex = e.Row.RowIndex;
}
currentId = itemId;
}
}
}
I've modified you code little bit by handling null conditions. Please have a look.
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
subTotal = 0;
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
int itemId = Convert.ToInt32(dt.Rows[e.Row.RowIndex]["ItemId"]);
total += Convert.ToDecimal(dt.Rows[e.Row.RowIndex]["Total"]);
if (itemId != currentId)
{
if (e.Row.RowIndex > 0)
{
for (int i = subTotalRowIndex; i < e.Row.RowIndex; i++)
{
Label lblViewTotal = (Label)e.Row.FindControl("lblViewTotal");//First Get label
if (lblViewTotal != null && lblViewTotal.Text != string.Empty) //Check whether it is null or not
{
subTotal += Convert.ToDecimal(lblViewTotal.Text);
}
}
this.AddTotalRow("Sub Total", subTotal.ToString("N7"));
subTotalRowIndex = e.Row.RowIndex;
}
currentId = itemId;
}
}
}
Are you sure that OnRowCreated Triggers after OnDataBound ?
It may be that there is no value at the stage when you are doing the sub total.
Try using the RowDataBound event instead?
(Been a while since I did web forms work, so this is from memory, apologies if I am incorrect)

CustomValidator not fired in gridview

I have a gridview and i'm trying to create an insert footer. The data inserted must be unique so i have created a custom validator. The problem is that i can;t fire the validator when I am pressing the linkbutton.
<asp:TemplateField HeaderText="id" SortExpression="id">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButtonInsert" runat="server" OnClick="updateData">Adauga</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="name" SortExpression="name">
<asp:TemplateField HeaderText="name" SortExpression="name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>' ></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Bind("name") %>' PostBackUrl='<%# "~/login.aspx?UserID=" + Eval("name") %>'>
</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator id="RequiredFieldValidator" runat="server" controlToValidate="TextBoxName" Text ="*" ValidationGroup = "INSERT"
ErrorMessage="Introduceti numele categoriei" forecolor="red"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="CustomValidatorText" runat="server" ErrorMessage="Exista deja categoria" controlToValidate="TextBoxName" ValidationGroup = "INSERT"
forecolor="red" OnServerValidate="CheckCategoryAvailability"></asp:CustomValidator>
</FooterTemplate>
</asp:TemplateField>
Here is the backgroud code:
protected void CheckCategoryAvailability(object source, ServerValidateEventArgs args)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
string textBoxName = ((CustomValidator)source).ControlToValidate;
var textBox = ((CustomValidator)source).Parent.FindControl(textBoxName) as TextBox;
string txt = textBox.Text;
Response.Write(textBox.Text);
SqlCommand com = new SqlCommand("select count(*) from Chapter where name = '" + txt +"';", con);
Response.Write(com.ExecuteScalar());
int temp = Int32.Parse(com.ExecuteScalar().ToString());
if (temp == 1)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
protected void updateData(object source, EventArgs args)
{
Response.Write(Page.IsValid);
}
You have to place the ValidationGroup attribute also in the LinkButton tag:
<asp:LinkButton ID="LinkButtonInsert" runat="server" OnClick="updateData" ValidationGroup="INSERT">Adauga</asp:LinkButton>
Easier Option
Copy custom Validator with different ID but calling the same function passes the textfield value as args parameter
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="txtBusinessName" ErrorMessage="Invalid Text Entered" CssClass="alert-danger" OnServerValidate="customvalidator1_ServerValidate"></asp:CustomValidator>
<asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="txtAddress1" ErrorMessage="Invalid Text Entered" CssClass="label-danger" OnServerValidate="customvalidator1_ServerValidate"></asp:CustomValidator>
Protected Sub customvalidator1_ServerValidate(source As Object, args As ServerValidateEventArgs)
If args.Value.contains("X") Then
args.IsValid = False
End If
End Sub

set a datavalue of a detailsView ' field programmatically

I want to set a value (Field IDCommerciale) when I click the insert button on a details view. I tried to change the value using OnItemInserting but nothing happens.
This is the code on the aspx:
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px" DefaultMode="Insert"
AutoGenerateRows="False" DataKeyNames="IDPianificazione"
DataSourceID="EntityDataSourceDetailsView" OnItemInserting="insertingmodeevent"
>
<Fields>
<asp:TemplateField HeaderText="IDCommerciale"
SortExpression="IDCommerciale">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Commerciali.Nome") %>'></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="ddlIDCommerciale" runat="server" SelectedValue='<%# Bind("IDCommerciale") %>'
DataSourceID="EntityDataSource1" DataTextField="Nome"
DataValueField='IDCommerciale'>
</asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="IDCLiente" SortExpression="IDCLiente">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("IDCLiente") %>'></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("IDCLiente") %>'></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="IDCategoria" SortExpression="IDCategoria">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("IDCategoria") %>'></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("IDCategoria") %>'></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Oggetto" HeaderText="Oggetto"
SortExpression="Oggetto" />
<asp:BoundField DataField="datainizio" HeaderText="datainizio"
SortExpression="datainizio" />
<asp:BoundField DataField="DataPresuntaFine" HeaderText="DataPresuntaFine"
SortExpression="DataPresuntaFine" />
<asp:BoundField DataField="DataCompletamento" HeaderText="DataCompletamento"
SortExpression="DataCompletamento" />
<asp:CommandField
ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
<asp:EntityDataSource ID="EntityDataSourceDetailsView" runat="server"
ConnectionString="name=SalesPortalEntities" Include="Categorie,Commerciali,Clienti"
DefaultContainerName="SalesPortalEntities" EnableDelete="True"
EnableFlattening="False" EnableInsert="True" EnableUpdate="True"
EntitySetName="PianificazioneIncontri">
</asp:EntityDataSource>
<asp:EntityDataSource ID="EntityDataSource1" runat="server"
ConnectionString="name=SalesPortalEntities"
DefaultContainerName="SalesPortalEntities" EnableFlattening="False"
EntitySetName="Commerciali">
</asp:EntityDataSource>
and this is the code behind:
protected void insertingmodeevent(object sender, EventArgs e)
{
string gruppoAdmin = System.Web.Security.FormsAuthentication.Decrypt(Request.Cookies[1].Value).UserData;
if (gruppoAdmin.Contains("SPGAdmins"))
{
try
{
DropDownList dd = new DropDownList();
dd = DetailsView1.FindControl("ddlIDCommerciale") as DropDownList;
dd.SelectedIndex = 1;
dd.SelectedValue = "1";
}
catch (Exception)
{
new Exception();
}
}
else
{
// other code
}
}
The code is execude regularly but if I check the data on the Database, the Item does'ent take the value forced on the code behind. I tried also with The event OnDataBinding but the result is the same.
How can I force the value for this field?
A possible solution is to add an event OnItemInserting on the entitydatasource of my gridview. Then I used this code:
protected void UpdateDataSource(object sender, EntityDataSourceChangingEventArgs e)
{
if (!gruppoAdmin.Contains("SPGAdmins"))
{
SalesPortalModel.PianificazioneIncontri pianificazione = e.Entity as SalesPortalModel.PianificazioneIncontri;
int idCommerciale = (from a in entity.Commerciali where a.Nome == Context.User.Identity.Name select a.IDCommerciale).First();
pianificazione.IDCommerciale = idCommerciale;
detailsView1.Rows[1].Visible = false;
}
}

Categories