CustomValidator not fired in gridview - c#

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

Related

Use child footer row to add new record to a nested gridview

I have a nested grid views:
<asp:GridView ID="gvRequisitions" runat="server" AutoGenerateColumns="false"
DataKeyNames="PurchaseRequisitionID" OnRowDataBound="OnRowDataBound" ShowFooter="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor:pointer" src="../images/plus.png" width="12" height="12" />
<asp:Panel ID="pnlItems" runat="server" Style="display: none">
<asp:GridView ID="gvItems" runat="server" AutoGenerateColumns="false" ShowFooter="true"
OnRowDataBound="gvItems_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblItemID" runat="server" Text='<%# Eval("ItemID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddItem" runat="server" OnClick="addItem" Text="add" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Code">
<ItemTemplate>
<asp:Label ID="lblItemCode" runat="server" Text='<%# Eval("ItemCode") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtItemCode" runat="server" Visible="true" Width="100"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description") %>'
Width="225"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDescription" runat="server" Width="225"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date req.">
<ItemTemplate>
<asp:Label ID="lblDateRequired" runat="server" Text='<%# Eval("DateRequired") %>'
Width="75"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDateRequired" runat="server" Width="75"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Measure">
<ItemTemplate>
<asp:Label ID="lblMeasure" runat="server" Text='<%# Eval("MeasureID") %>'
Width="120" ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlMeasure" runat="server" Width="120"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Qty">
<ItemTemplate>
<asp:Label ID="lblQuantity" runat="server" Text='<%# Eval("Quantity") %>' Width="75"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtQuantity" runat="server" Width="75"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cost">
<ItemTemplate>
<asp:Label ID="lblCostPerUnit" runat="server" Text='<%# Eval("CostPerUnit") %>' Width="75"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCostPerUnit" runat="server" Width="75"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server" Text='<%# Eval("Total") %>' Width="120"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>No Items For this Requisition</EmptyDataTemplate>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblPurchaseRequisitionID" runat="server" Text='<%# Eval("PurchaseRequisitionID") %>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddReq" runat="server" Text="Add" OnClick="addPurreq" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Requested By">
<ItemTemplate>
<asp:Label ID="lblRequestor" runat="server" Text='<%# Eval("Requestor") %>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlRequestor" runat="server" Width="200"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<asp:Label ID="lblDepartmentID" runat="server" Text='<%# Eval("DepartmentID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDepartment" runat="server" Width="200" ></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Budget">
<ItemTemplate>
<asp:Label ID="lblBudgetID" runat="server" Text='<%# Eval("BudgetID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlBudget" runat="server" Width="200"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Supplier">
<ItemTemplate>
<asp:Label ID="lblSupplierID" runat="server" Text='<%# Eval("SupplierID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlSupplier" runat="server" Width="200"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created">
<ItemTemplate>
<asp:Label ID="lblDateCreated" runat="server" Text='<%# Eval("DateCreated","{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In code behind I have:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
string purchaseRequisitionID = gvRequisitions.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvItems = (GridView)e.Row.FindControl("gvItems");
// new code to send reference to gvItems_RowDataBound
gvItems.RowDataBound += new GridViewRowEventHandler(gvItems_RowDataBound);
int id = Convert.ToInt32(purchaseRequisitionID);
using (SqlConnection conn = new SqlConnection(constr))
{
using(SqlCommand comm = new SqlCommand("procItems_CRUD"))
{
comm.Parameters.AddWithValue("#Action", "SELECT");
comm.Parameters.AddWithValue("#ID", id);
using(SqlDataAdapter sda = new SqlDataAdapter())
{
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
sda.SelectCommand = comm;
using(DataTable dt = new DataTable())
{
sda.Fill(dt);
gvItems.DataSource = dt;
gvItems.DataBind();
}
}
}
}
}
}
And:
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlMeasure = e.Row.FindControl("ddlMeasure") as DropDownList;
if(ddlMeasure == null)
{
}
}
}
But I cannot see the drop down list as it returns a null value (as I know it is not a DataRow) but how can I see the footer row and the elements in footer row so that I can add another Item to the order/populate DropDownList etc.
Have been trying to sort this for some time and cannot find a working solution so any pointer(s) will be very much appreciated.
You need to use DataControlRowType.Footer.
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a footer row
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlMeasure = e.Row.FindControl("ddlMeasure") as DropDownList;
if (ddlMeasure != null)
{
ddlMeasure.Items.Insert(0, new ListItem("DLL Found!", "-1"));
}
}
}

Unable to cast object of type 'AllProjects_Result' to type 'Project'

i found many article and i make this code
i have this error
Unable to cast object of type 'AllProjects_Result' to type 'Project'.
<asp:GridView ID="GVAllProjects" runat="server"
OnRowDataBound="GVAllProjects_RowDataBound"
OnRowDeleting="GVAllProjects_RowDeleting"
OnRowEditing="GVAllProjects_RowEditing"
OnRowUpdating="GVAllProjects_RowUpdating"
AutoGenerateColumns="False" AllowPaging="True" PageSize="5" DataKeyNames="ID">
<Columns>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150" />
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblProID" Visible="false" runat="server" Text='<%# Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="المشروعات" ItemStyle-Width="150" >
<ItemTemplate>
<asp:Label ID="lblProjectName" runat="server" Text='<%# Eval("ProjectName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProjectName" runat="server" Text='<%# Eval("ProjectName") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="الموقع" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblDistrictName" runat="server" Text='<%# Eval("DistrictName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlDistrictName" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="valDistrictName" runat="server" ControlToValidate="ddlDistrictName"
Display="Dynamic" ErrorMessage="DistrictName is required." ForeColor="Red" SetFocusOnError="True"
ValidationGroup="editGrp">*</asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDistrictNameNew" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="valDistrictNameNew" runat="server" ControlToValidate="ddlDistrictNameNew"
Display="Dynamic" ErrorMessage="DistrictName is required." ForeColor="Red" SetFocusOnError="True"
ValidationGroup="newGrp">*</asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="المساحات" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblAreas" runat="server" Text='<%# Eval("Areas")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAreas" runat="server" Text='<%# Eval("Areas") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="نظام السداد" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblPaymentSystem" runat="server" Text='<%# Eval("PaymentSystem")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPaymentSystem" runat="server" Text='<%# Eval("PaymentSystem") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="تاريخ الاستلام" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblReceivedDate" runat="server" Text='<%# Eval("ReceivedDate", "{0:d}")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditDate" runat="server"></asp:TextBox>
<asp:ImageButton runat="server" ID="imgPopup" ImageUrl="~/images/-calendar.png" ImageAlign="Bottom" />
<ajaxToolkit:calendarextender popupbuttonid="imgPopup" id="CalendarExtender1" runat="server" targetcontrolid="txtEditDate"
format="MM/dd/yyyy" enabled="true" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddDate" runat="server"></asp:TextBox>
<asp:ImageButton runat="server" ID="imgPopup" ImageUrl="~/images/-calendar.png" ImageAlign="Bottom" />
<ajaxToolkit:calendarextender id="CalendarExtender2" runat="server"
targetcontrolid="txtAddDate" popupbuttonid="imgPopup" enabled="true" format="dd/MM/yyyy" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="تصنيف العقار" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblClassification" runat="server" Text='<%# Eval("PropertyClassification")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtClassification" runat="server" Text='<%# Eval("PropertyClassification") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="صورة المشروع" ItemStyle-Width="150">
<ItemTemplate>
<img src='ProjectsImages/<%# Eval("ProjectImage") %>' style="width:120px;height:120px;" />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="UploadPhoto" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="الغرض" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblPurposeName" runat="server" Text='<%# Bind("PurposeName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlPurposeName" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="valPurposeName" runat="server" ControlToValidate="ddlPurposeName"
Display="Dynamic" ErrorMessage="PurposeName is required." ForeColor="Red" SetFocusOnError="True"
ValidationGroup="editGrp">*</asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlPurposeNameNew" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="valClassificationNew" runat="server" ControlToValidate="ddlPurposeNameNew"
Display="Dynamic" ErrorMessage="DistrictName is required." ForeColor="Red" SetFocusOnError="True"
ValidationGroup="newGrp">*</asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="النوع" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblTypes" runat="server" Text='<%# Bind("TypeName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlTypes" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="valTypes" runat="server" ControlToValidate="ddlTypes"
Display="Dynamic" ErrorMessage="Types is required." ForeColor="Red" SetFocusOnError="True"
ValidationGroup="editGrp">*</asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlTypesNew" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="valTypesNew" runat="server" ControlToValidate="ddlTypesNew"
Display="Dynamic" ErrorMessage="Types is required." ForeColor="Red" SetFocusOnError="True"
ValidationGroup="newGrp">*</asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and this is my code :
protected void GVAllProjects_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList ddlDistrictName = null;
DropDownList ddlPurposeName = null;
DropDownList ddlTypes = null;
if (e.Row.RowType == DataControlRowType.Footer)
{
ddlDistrictName = e.Row.FindControl("ddlDistrictNameNew") as DropDownList;
ddlPurposeName = e.Row.FindControl("ddlPurposeNameNew") as DropDownList;
ddlTypes = e.Row.FindControl("ddlTypesNew") as DropDownList;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
ddlDistrictName = e.Row.FindControl("ddlDistrictName") as DropDownList;
ddlPurposeName = e.Row.FindControl("ddlPurposeName") as DropDownList;
ddlTypes = e.Row.FindControl("ddlTypes") as DropDownList;
}
if (ddlDistrictName != null)
{
using (AlamaarRealEstateEntities context = new AlamaarRealEstateEntities())
{
ddlDistrictName.DataSource = context.Districts.ToList();
ddlDistrictName.DataTextField = "DistrictName";
ddlDistrictName.DataValueField = "ID";
ddlDistrictName.DataBind();
ddlPurposeName.Items.Insert(0, new ListItem(""));
ddlPurposeName.DataSource = context.Purposes.ToList();
ddlPurposeName.DataTextField = "PurposeName";
ddlPurposeName.DataValueField = "ID";
ddlPurposeName.DataBind();
ddlTypes.Items.Insert(0, new ListItem(""));
ddlTypes.DataSource = context.Types.ToList();
ddlTypes.DataTextField = "TypeName";
ddlTypes.DataValueField = "ID";
ddlTypes.DataBind();
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
ddlDistrictName.SelectedValue = ((Project)(e.Row.DataItem)).DistrictID.ToString();
ddlPurposeName.SelectedValue = ((Project)(e.Row.DataItem)).PurposeID.ToString(); ;
ddlTypes.SelectedValue = ((Project)(e.Row.DataItem)).TypeID.ToString();
}
}
}
}
void BindGrid()
{
using (AlamaarRealEstateEntities context = new AlamaarRealEstateEntities())
{
if (context.Projects.Count() > 0)
{
GVAllProjects.DataSource = context.AllProjects().ToList();
GVAllProjects.DataBind();
}
else
{
var obj = new List<Project>();
obj.Add(new Project());
// Bind the DataTable which contain a blank row to the GridView
GVAllProjects.DataSource = obj;
GVAllProjects.DataBind();
int columnsCount = GVAllProjects.Columns.Count;
GVAllProjects.Rows[0].Cells.Clear();// clear all the cells in the row
GVAllProjects.Rows[0].Cells.Add(new TableCell()); //add a new blank cell
GVAllProjects.Rows[0].Cells[0].ColumnSpan = columnsCount; //set the column span to the new added cell
//You can set the styles here
GVAllProjects.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
GVAllProjects.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;
GVAllProjects.Rows[0].Cells[0].Font.Bold = true;
//set No Results found to the new added cell
GVAllProjects.Rows[0].Cells[0].Text = "NO RESULT FOUND!";
}
}
}
the error here in this lines :
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
ddlDistrictName.SelectedValue = ((Project)(e.Row.DataItem)).DistrictID.ToString();
ddlPurposeName.SelectedValue = ((Project)(e.Row.DataItem)).PurposeID.ToString(); ;
ddlTypes.SelectedValue = ((Project)(e.Row.DataItem)).TypeID.ToString();
}
}
any help is appreciated.

on add button click data insert twice

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyManageConnectionString"].ToString());
string InstituteId = HttpContext.Current.Request.Cookies["InstituteId"].Value;
protected void Page_Load(object sender, EventArgs e)
{
((Label)Master.FindControl("lblPageName")).Text = "Employee List";
((Label)Master.FindControl("lblPageName")).ForeColor = System.Drawing.Color.Black;
((Label)Master.FindControl("lblPageName1")).Text = " Employee List";
if (Request.Cookies["InstituteId"] == null)
{
string OriginalUrl = HttpContext.Current.Request.RawUrl;
string LoginPageUrl = "INlogin.aspx";
HttpContext.Current.Response.Redirect(String.Format("{0}?R={1}", LoginPageUrl, OriginalUrl));
}
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
string strQuery = "select * from tblEmployee where InstituteId=#InstituteId";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#InstituteId", InstituteId);
gvEmpList.DataSource = GetData(cmd);
gvEmpList.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
//SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
protected void btnAdd_Click(object sender, EventArgs e)
{
string ActivationCode = Guid.NewGuid().ToString();
string txtEmployeeName = ((TextBox)gvEmpList.FooterRow.FindControl("txtEmployeeName")).Text;
string txtEmployeeAddress = ((TextBox)gvEmpList.FooterRow.FindControl("txtEmployeeAddress")).Text;
string txtEmployeeEmailId = ((TextBox)gvEmpList.FooterRow.FindControl("txtEmployeeEmailId")).Text;
string txtMobile = ((TextBox)gvEmpList.FooterRow.FindControl("txtMobile")).Text;
string txtBirthDate = ((TextBox)gvEmpList.FooterRow.FindControl("txtBirthDate")).Text;
string txtdateOfJoining = ((TextBox)gvEmpList.FooterRow.FindControl("txtdateOfJoining")).Text;
string txtExperiance = ((TextBox)gvEmpList.FooterRow.FindControl("txtExperiance")).Text;
string txtLastSchoolDetails = ((TextBox)gvEmpList.FooterRow.FindControl("txtLastSchoolDetails")).Text;
string txtSalaryDetails = ((TextBox)gvEmpList.FooterRow.FindControl("txtSalaryDetails")).Text;
bool chkmerriageStatus = ((CheckBox)gvEmpList.FooterRow.FindControl("chkmerriageStatus")).Checked;
string txtNationality = ((TextBox)gvEmpList.FooterRow.FindControl("txtNationality")).Text;
try
{
//SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
//con.Open();
//cmd.Connection = con;
cmd.CommandText = "INSERT INTO tblEmployee (InstituteId, EmployeeName, EmployeeAddress, EmployeeEmailId, Mobile, BirthDate, dateOfJoining, Experiance, LastSchoolDetails, SalaryDetails, merriageStatus, Nationality, ActivationCode, ActivationStatus, Password) VALUES (#InstituteId, #EmployeeName, #EmployeeAddress, #EmployeeEmailId, #Mobile, #BirthDate, #dateOfJoining, #Experiance, #LastSchoolDetails, #SalaryDetails, #merriageStatus, #Nationality, #ActivationCode, #ActivationStatus, #Password);" + "select * from tblEmployee where InstituteId=#InstituteId";
cmd.Parameters.AddWithValue("#InstituteId", InstituteId);
cmd.Parameters.AddWithValue("#EmployeeName", txtEmployeeName);
cmd.Parameters.AddWithValue("#EmployeeAddress", txtEmployeeAddress);
cmd.Parameters.AddWithValue("#EmployeeEmailId", txtEmployeeEmailId);
cmd.Parameters.AddWithValue("#Mobile", txtMobile);
cmd.Parameters.AddWithValue("#BirthDate", txtBirthDate);
cmd.Parameters.AddWithValue("#dateOfJoining", txtdateOfJoining);
cmd.Parameters.AddWithValue("#Experiance", txtExperiance);
cmd.Parameters.AddWithValue("#LastSchoolDetails", txtLastSchoolDetails);
cmd.Parameters.AddWithValue("#SalaryDetails", txtSalaryDetails);
cmd.Parameters.AddWithValue("#merriageStatus", chkmerriageStatus);
cmd.Parameters.AddWithValue("#Nationality", txtNationality);
cmd.Parameters.AddWithValue("#ActivationCode", ActivationCode);
cmd.Parameters.AddWithValue("#ActivationStatus", false);
string GTPassword = System.Web.Security.Membership.GeneratePassword(8, 3);
cmd.Parameters.AddWithValue("#Password", GTPassword);
//int result = cmd.ExecuteNonQuery();
//con.Close();
//if (result == 1)
//{
// sendActivation(ActivationCode, txtEmployeeName, txtEmployeeEmailId);
// Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Registration Successfull')", true);
//}
//else {
// Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Registration Fail')", true);
//}
gvEmpList.DataSource = GetData(cmd);
gvEmpList.DataBind();
//BindData();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
When the add button is clicked btnAdd_click inserts data twice. Also I am not getting any exception errors in btnadd_click code.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="dvGrid" style="overflow-x: scroll; Overflow: scroll;">
<asp:UpdatePanel ID="upEmployeeList" runat="server">
<ContentTemplate>
<asp:GridView Width="100%" ID="gvEmpList" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeId" CssClass="gvmydatagrid" PagerStyle-CssClass="gvpager" HeaderStyle-CssClass="gvheader" RowStyle-CssClass="gvrows" ShowFooter="True" OnPageIndexChanging="gvEmpList_PageIndexChanging" OnRowEditing="gvEmpList_RowEditing" OnRowUpdating="gvEmpList_RowUpdating" OnRowCancelingEdit="gvEmpList_RowCancelingEdit" AllowPaging="True" PageSize="25">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument='<%# Eval("EmployeeId")%>'
OnClientClick="return confirm('Do you want to delete?')"
Text="Delete" OnClick="lnkRemove_Click"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="EmployeeId" InsertVisible="False" SortExpression="EmployeeId">
<EditItemTemplate>
<asp:Label ID="lblEmployeeId" runat="server" Text='<%# Eval("EmployeeId") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeId" runat="server" Text='<%# Bind("EmployeeId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<%-- <asp:TemplateField HeaderText="InstituteId" SortExpression="InstituteId">
<EditItemTemplate>
<asp:Label ID="txtInstituteId" runat="server" Text='<%# Bind("InstituteId") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblInstituteId" runat="server" Text='<%# Bind("InstituteId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="EmployeeName" SortExpression="EmployeeName">
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("EmployeeName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeName" runat="server" Text='<%# Bind("EmployeeName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EmployeeAddress" SortExpression="EmployeeAddress">
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeAddress" runat="server" Text='<%# Bind("EmployeeAddress") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeeAddress" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeAddress" runat="server" Text='<%# Bind("EmployeeAddress") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EmployeeEmailId" SortExpression="EmployeeEmailId">
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeEmailId" runat="server" Text='<%# Bind("EmployeeEmailId") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeeEmailId" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeEmailId" runat="server" Text='<%# Bind("EmployeeEmailId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile" SortExpression="Mobile">
<EditItemTemplate>
<asp:TextBox ID="txtMobile" runat="server" Text='<%# Bind("Mobile") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblMobile" runat="server" Text='<%# Bind("Mobile") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="BirthDate" SortExpression="BirthDate">
<EditItemTemplate>
<asp:TextBox ID="txtBirthDate" runat="server" Text='<%# Bind("BirthDate") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBirthDate" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblBirthDate" runat="server" Text='<%# Bind("BirthDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="dateOfJoining" SortExpression="dateOfJoining">
<EditItemTemplate>
<asp:TextBox ID="txtdateOfJoining" runat="server" Text='<%# Bind("dateOfJoining") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtdateOfJoining" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbldateOfJoining" runat="server" Text='<%# Bind("dateOfJoining") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Experiance" SortExpression="Experiance">
<EditItemTemplate>
<asp:TextBox ID="txtExperiance" runat="server" Text='<%# Bind("Experiance") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtExperiance" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblExperiance" runat="server" Text='<%# Bind("Experiance") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastSchoolDetails" SortExpression="LastSchoolDetails">
<EditItemTemplate>
<asp:TextBox ID="txtLastSchoolDetails" runat="server" Text='<%# Bind("LastSchoolDetails") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLastSchoolDetails" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblLastSchoolDetails" runat="server" Text='<%# Bind("LastSchoolDetails") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SalaryDetails" SortExpression="SalaryDetails">
<EditItemTemplate>
<asp:TextBox ID="txtSalaryDetails" runat="server" Text='<%# Bind("SalaryDetails") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtSalaryDetails" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblSalaryDetails" runat="server" Text='<%# Bind("SalaryDetails") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="merriageStatus" SortExpression="merriageStatus">
<EditItemTemplate>
<asp:CheckBox ID="chkmerriageStatus" runat="server" Checked='<%# Bind("merriageStatus") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkmerriageStatus" runat="server"></asp:CheckBox>
</FooterTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkmerriageStatus" runat="server" Checked='<%# Bind("merriageStatus") %>' Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nationality" SortExpression="Nationality">
<EditItemTemplate>
<asp:TextBox ID="txtNationality" runat="server" Text='<%# Bind("Nationality") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNationality" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblNationality" runat="server" Text='<%# Bind("Nationality") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Password" SortExpression="Password">
<EditItemTemplate>
<asp:TextBox ID="txtPassword" runat="server" Text='<%# Bind("Password") %>'></asp:TextBox>
</EditItemTemplate>
<%--<FooterTemplate>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</FooterTemplate>--%>
<ItemTemplate>
<asp:Label ID="lblPassword" runat="server" Text='<%# Bind("Password") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="gvheader" />
<PagerStyle CssClass="gvpager" />
<RowStyle CssClass="gvrows" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gvEmpList" />
</Triggers>
</asp:UpdatePanel>
</div>
When I click on add button, footer item data will insert into my database but is insert twice. It is in debug mode and jumping around everywhere.
it show "The process or thread has changed since last step."
You are sending the insert command again by calling gvEmpList.DataSource = GetData(cmd); inside btnAdd_Click. Please check it. The cmd object inside btnAdd_Click is an insert command.
Remove following code from btnAdd_Click
gvEmpList.DataSource = GetData(cmd);
gvEmpList.DataBind();
And call following method
BindData();

disable textbox in edit mode

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

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)

Categories