Use Checkbox to Insert or Delete a row in Database - c#

I am trying to update a single record in a DataList. I have chosen the DataList type so that I can have a horizontal row with many records on the same page, can use the page to take attendance from a pre-determined list of people, but I want to update as I go. I will be using volunteers to take attendance and don't want to force the users to click save after they are finished (They may get distracted and forget to do so). So, each check box marks a person present. Or unchecking marks them absent.
Here is my CSHTML page:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="AttendanceTaking.aspx.cs" Inherits="AtChurch.AttendanceTaking" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<style>.ChkBoxClass input {width:25px; height:25px;}
.auto-style1 {
width: 32px;
}
.auto-style2 {
width: 183px;
}
</style>
<table>
<tr>
<td class="auto-style2"><strong>Take Attendance</strong></td>
<td class="auto-style1">Date:</td>
<td>
<strong>
<asp:Label ID="lblAttendanceDate" runat="server"></asp:Label>
</strong>
</td>
<td>
Attendance Group:</td>
<td>
<strong>
<asp:Label ID="lblAttendanceGroup" runat="server" ></asp:Label>
</strong>
</td>
</tr>
</table>
<p>
<asp:HiddenField ID="HiddenAttendanceDate" runat="server" />
<asp:HiddenField ID="HiddenSoCID" runat="server" />
</p>
<p>
<asp:DataList RepeatDirection="Horizontal" RepeatColumns="6" ID="DataList1" runat="server" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="DataList1_SelectedIndexChanged" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Both">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<ItemStyle ForeColor="#000066" />
<ItemTemplate>
<asp:CheckBox ID="CheckBoxPresent" runat="server" RowNumber='<%# Eval("RowNumber") %>' AttendanceID='<%# Eval("AttendanceID") %>' PeopleId='<%# Eval("PeopleID") %>' Text='<%# Eval("CheckBoxPresent") %>' Checked='<%# Eval("CheckBoxPresent").ToString().Equals("1") %>' CssClass="ChkBoxClass" OnCheckedChanged="CheckBoxPresent_CheckedChanged" AutoPostBack="true" />
<asp:Label ID="RowNumber" runat="server" Text='<%# Eval("RowNumber") %>' />
<asp:Label ID="FullName" runat="server" Text='<%# Eval("FullName") %>' />
<asp:Label ID="PeopleID" runat="server" Text='<%# Eval("PeopleID") %>' />
<asp:Label ID="AttendanceID" runat="server" Text='<%# Eval("AttendanceID") %>' ></asp:Label>
<asp:Label ID="AttendLabel" runat="server" Text="&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"></asp:Label> <br />
<br />
</ItemTemplate>
<SelectedItemStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<FooterTemplate>
:
</FooterTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AtChurchConString %>" SelectCommand="sp_AttendanceTaking" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="ChurchID" DefaultValue="0" Name="ChurchID" PropertyName="Value" />
<asp:ControlParameter ControlID="HiddenSoCID" DefaultValue="0" Name="HiddenSoCID" PropertyName="Value" />
<asp:Parameter DefaultValue="1" Name="Select" Type="Int32" />
<asp:ControlParameter ControlID="HiddenAttendanceDate" DefaultValue="" Name="AttendanceDate" PropertyName="Value" Type="DateTime" />
<%--<asp:ControlParameter ControlID="CheckBoxPresent" DefaultValue="0" Name="CheckBoxPresent" PropertyName="Value" />--%>
<%-- <asp:ControlParameter ControlID="AttendanceID" DefaultValue="0" Name="AttendanceID" PropertyName="Value" />--%>
<%--<asp:ControlParameter ControlID="PeopleID" DefaultValue="0" Name="PeopleID" PropertyName="Value" />--%>
</SelectParameters>
</asp:SqlDataSource>
<asp:HiddenField ID="ChurchID" runat="server" />
</p>
<p>
</p>
</asp:Content>
And here is my CS page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Web.SessionState;
namespace AtChurch
{
public partial class AttendanceTaking : System.Web.UI.Page
{
private static string strcon = WebConfigurationManager.ConnectionStrings["AtChurchConString"].ConnectionString;
// Need these for Security
public string strRole, strChurchID, strAttGroup, strAttDate;
public bool ValidUser { get; private set; }
// Checkbox Checked?
protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
{
//start of checkbox
CheckBox ChkBxPresent = sender as CheckBox;
Boolean ChkBxPresentState = ChkBxPresent.Checked;
//DataList1.DataBind();
foreach (DataListItem itm in DataList1.Items)
{
if (itm.ItemType == ListItemType.Item )
{
string strPeopleID = ((Label)itm.FindControl("PeopleID")).Text;
string strAttendanceID = ((Label)itm.FindControl("AttendanceID")).Text;
Response.Write(strPeopleID);
Response.End();
//string strAttID = "";
//strAttID = ((DataBoundLiteralControl)item.Controls[1]).Text;
if (ChkBxPresentState == true)
{
Response.Write("Let's Insert it...");
Response.Write(strPeopleID);
Response.End();
}
else
{
//Response.Write("Let's Remove it...");
//Response.End();
SqlConnection con = new SqlConnection(strcon);
// First let's delete this Groups Data
SqlCommand cmdDelete = new SqlCommand("sp_AttendanceTaking", con);
cmdDelete.CommandType = CommandType.StoredProcedure;
//cmdDelete.Parameters.Add(new SqlParameter("#HiddenSoCID", SqlDbType.Int));
cmdDelete.Parameters.Add(new SqlParameter("#AttendanceID", SqlDbType.Int));
//cmdDelete.Parameters.Add(new SqlParameter("#ChurchID", SqlDbType.Int));
//cmdDelete.Parameters.Add(new SqlParameter("#AttendanceDate", SqlDbType.DateTime));
cmdDelete.Parameters.Add(new SqlParameter("#CheckBoxPresent", SqlDbType.Int));
//cmdDelete.Parameters.Add(new SqlParameter("#PeopleID", SqlDbType.Int));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttendanceID.ToString(), out int intAttendanceID)) { }
Response.Write(intAttendanceID);
Response.Write("-");
Response.Write(1);
Response.End();
cmdDelete.Parameters["#AttendanceID"].Value = intAttendanceID;
cmdDelete.Parameters["#CheckBoxPresent"].Value = 0;
con.Open();
cmdDelete.ExecuteNonQuery();
con.Close();
// End delete data
}
}
}
//end of checkbox
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
if (!IsPostBack)
{
// Get Attendance Group ID from the Attendance page.
//if (Request.QueryString["SoCID"].ToString() != null && Request.QueryString["SoCID"].ToString() != null)
string SoCID = Server.UrlDecode(Request.QueryString["SoCID"]);
string AttendanceDate = Server.UrlDecode(Request.QueryString["AttendanceDate"]);
// Response.Write("ok?"+AttendanceDate);
// Response.End();
if (SoCID != null && AttendanceDate != null)
{
strAttGroup = SoCID;
HiddenSoCID.Value = strAttGroup;
lblAttendanceGroup.Text = strAttGroup;
strAttDate = AttendanceDate;
HiddenAttendanceDate.Value = strAttDate;
lblAttendanceDate.Text = strAttDate;
//strAttDate = Request.QueryString["AttendanceDate"].ToString();
//Response.Write(strAttGroup);
//Response.Write(strAttDate);
//Response.End();
}
else
{
//Response.Write("error");
Response.Redirect("Attendance.aspx");
Response.End();
}
}
// Security Start
if (Session["Role"] is null && Session["ChurchID"] is null)
{
Response.Redirect("Login.aspx");
return;
}
if (Session["Role"] != null && Session["ChurchID"] != null)
{
if (!string.IsNullOrEmpty(Session["Role"].ToString()))
{
strRole = Session["Role"].ToString();
strChurchID = Session["ChurchID"].ToString();
}
}
if (strRole == ("SuperAdmin") || strRole == ("ChurchAdmin"))
{
ValidUser = true;
}
if (ValidUser != true)
{
Response.Redirect("Login.aspx");
}
// Security End
//Populate the ChurchID for Insert
ChurchID.Value = strChurchID;
}
protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button_AttendanceTaker_Command(object sender, CommandEventArgs e)
{
}
}
}
This is just the button code of which I am working with to add or delete using my stored procedure.
protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
{
//start of checkbox
CheckBox ChkBxPresent = sender as CheckBox;
Boolean ChkBxPresentState = ChkBxPresent.Checked;
// I added this to try to compare to to get a specific row for Insert
string BoxIndex = ChkBxPresent.Attributes["RowNumber"];
//DataList1.DataBind();
foreach (DataListItem itm in DataList1.Items)
{
// I added this to try to compare to within the Item List
string ItmIndex = ((Label)itm.FindControl("RowNumber")).Text;
if (itm.ItemType == ListItemType.Item)
{
// Let's gather the parameter data needed
string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
string strAttendanceID = ChkBxPresent.Attributes["AttendanceID"];
string strCheckBoxPresent = ChkBxPresent.Attributes["IsChecked"];
string strAttGroupID = ((Label)itm.FindControl("SoCID")).Text;
string strAttendanceDate = ((Label)itm.FindControl("AttendanceDate")).Text;
// Here is what we do if the box is checked...
// I used this to try and compare the values. It showed the one I wanted to
// compare to but the ItmIndex only returned odd rows. So I don't match somtimes
//Response.Write("BoxIdx=");
//Response.Write(BoxIndex);
//Response.Write("and ItmIdx=");
//Response.Write(ItmIndex);
// I added the compare of ItmIndex == BoxIndex but it was not consistent. Again it was only returning odd
// numbers and no even numbers to compare to for some reason.
if (ChkBxPresentState == true)
{
string strAction = "ADD";
//Response.Write("Add BoxIdx=");
//Response.Write(BoxIndex);
//Response.Write("and ItmIdx=");
//Response.Write(ItmIndex);
SqlConnection con = new SqlConnection(strcon);
//Response.Write("Let's Insert it...");
//Response.Write("PeopleID");
//Response.Write(strPeopleID);
//Response.Write("ChurchID");
//Response.Write(strChurchID);
//Response.Write("GroupID");
//Response.Write(strAttGroupID);
//Response.Write("AttDate");
//Response.Write(strAttendanceDate);
//Response.Write("Action");
//Response.Write(strAction);
//Response.End();
SqlCommand cmdInsertData = new SqlCommand("sp_AttendanceTaking", con);
cmdInsertData.CommandType = CommandType.StoredProcedure;
cmdInsertData.Parameters.Add(new SqlParameter("#AttGroupID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
cmdInsertData.Parameters.Add(new SqlParameter("#PeopleID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#ChurchID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#AttendanceDate", SqlDbType.DateTime));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttGroupID.ToString(), out int intGroupID)) { }
if (Int32.TryParse(strPeopleID.ToString(), out int intPeopleID)) { }
if (Int32.TryParse(strChurchID.ToString(), out int intChurchID)) { }
//Response.Write(intAttendanceID);
//Response.Write("-");
//Response.Write(strAction);
//Response.End();
cmdInsertData.Parameters["#AttGroupID"].Value = intGroupID;
cmdInsertData.Parameters["#Action"].Value = strAction;
cmdInsertData.Parameters["#PeopleID"].Value = intPeopleID;
cmdInsertData.Parameters["#ChurchID"].Value = intChurchID;
cmdInsertData.Parameters["#AttendanceDate"].Value = strAttendanceDate;
con.Open();
cmdInsertData.ExecuteNonQuery();
con.Close();
}
else
{
string strAction = "DEL";
//Response.Write("DEL BoxIdx=");
//Response.Write(BoxIndex);
//Response.Write("and ItmIdx=");
//Response.Write(ItmIndex);
//Response.Write(" |");
// Here is what we do if the Box is unchecked
//Response.Write("Let's Remove it...");
//Response.Write(strPeopleID);
//Response.Write("aID");
//Response.Write(strAttendanceID);
//Response.Write("checkBoxPresent:");
//Response.Write(strCheckBoxPresent);
//Response.End();
SqlConnection con = new SqlConnection(strcon);
// First let's delete this Groups Data
SqlCommand cmdDelete = new SqlCommand("sp_AttendanceTaking", con);
cmdDelete.CommandType = CommandType.StoredProcedure;
cmdDelete.Parameters.Add(new SqlParameter("#AttendanceID", SqlDbType.Int));
cmdDelete.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttendanceID.ToString(), out int intAttendanceID)) { }
//Response.Write(intAttendanceID);
//Response.Write("-");
//Response.Write(strAction);
//Response.End();
cmdDelete.Parameters["#AttendanceID"].Value = intAttendanceID;
cmdDelete.Parameters["#Action"].Value = strAction;
con.Open();
cmdDelete.ExecuteNonQuery();
con.Close();
// End delete data
}
}
}
//end of checkbox
}
It's obviously not complete as I'm just trying to get it to show the right data. I did a test of the delete portion (When the box is unchecked) and it did not delete a specific record because the EventArgs returns all the checkbox values. If I change it to DataListItemEventArgs it returns specific rows but then I lose the functionality of the checkbox on check. I think I need to separate these but I am not sure how to accomplish this task.
Here is the functionality I am going for:
1. Setup the date and retrieve any attendance if already taken.
Image of form that loads the AttendanceTaker
And a sample of the page I am going for with a large checkbox so it can be used on a tablet.
Sample of AttendanceTaker page
I rewrote the code using the idea from selected answer. This was the code that ended up working.
// Checkbox Checked?
protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
{
CheckBox ChkBxPresent = sender as CheckBox;
Boolean ChkBxPresentState = ChkBxPresent.Checked;
if (Int32.TryParse(ChkBxPresent.Attributes["AttendanceID"].ToString(), out int intAttendanceID)) { }
// Let's gather the parameter data needed
string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
string strAttendanceID = ChkBxPresent.Attributes["AttendanceID"];
string strCheckBoxPresent = ChkBxPresent.Attributes["IsChecked"];
string strAttGroupID = ChkBxPresent.Attributes["SoCID"];
string strAttendanceDate = ChkBxPresent.Attributes["AttendanceDate"];
if (intAttendanceID == 0) // Add Attendance Record it does not exist and was checked
{
string strAction = "ADD";
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmdInsertData = new SqlCommand("sp_AttendanceTaking", con);
cmdInsertData.CommandType = CommandType.StoredProcedure;
cmdInsertData.Parameters.Add(new SqlParameter("#AttGroupID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
cmdInsertData.Parameters.Add(new SqlParameter("#PeopleID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#ChurchID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#AttendanceDate", SqlDbType.DateTime));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttGroupID.ToString(), out int intGroupID)) { }
if (Int32.TryParse(strPeopleID.ToString(), out int intPeopleID)) { }
if (Int32.TryParse(strChurchID.ToString(), out int intChurchID)) { }
cmdInsertData.Parameters["#AttGroupID"].Value = intGroupID;
cmdInsertData.Parameters["#Action"].Value = strAction;
cmdInsertData.Parameters["#PeopleID"].Value = intPeopleID;
cmdInsertData.Parameters["#ChurchID"].Value = intChurchID;
cmdInsertData.Parameters["#AttendanceDate"].Value = strAttendanceDate;
con.Open();
cmdInsertData.ExecuteNonQuery();
con.Close();
DataList1.DataBind();
}
else // Delete Attendance Record it was unchecked
{
string strAction = "DEL";
SqlConnection con = new SqlConnection(strcon);
// First let's delete this Groups Data
SqlCommand cmdDelete = new SqlCommand("sp_AttendanceTaking", con);
cmdDelete.CommandType = CommandType.StoredProcedure;
cmdDelete.Parameters.Add(new SqlParameter("#AttendanceID", SqlDbType.Int));
cmdDelete.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
cmdDelete.Parameters["#AttendanceID"].Value = intAttendanceID;
cmdDelete.Parameters["#Action"].Value = strAction;
con.Open();
cmdDelete.ExecuteNonQuery();
con.Close();
DataList1.DataBind();
// End delete data
}
////end of checkbox

You can pass the value of the PeopleId (and/or attendanceID) in the checkbox as an attribute and avoid iterating over the DataList.
Your checkbox
<asp:CheckBox ID="CheckBoxPresent" runat="server" PeopleId='<%# Eval("PeopleID") %>' Text='<%# Eval("CheckBoxPresent") %>' Checked='<%# Eval("CheckBoxPresent").ToString().Equals("1") %>' CssClass="ChkBoxClass" OnCheckedChanged="CheckBoxPresent_CheckedChanged" AutoPostBack="true" />
Code behind
string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
Then if it's checked, issue insert command for that ID only, if it's unchecked, issue delete command for that ID.

Related

Edit, cancel and delete asp.net c#

ASPX:
<asp:GridView runat="server" ID="gv_localidad" AutoGenerateColumns="false">
<asp:TemplateField HeaderText="Modify">
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Editar" OnClick="OnEdit" Visible="true" />
<asp:Button ID="btnUpdate" runat="server" Text="Update" Visible="false" />
<asp:Button ID="btnDelete" runat="server" Text="Eliminar" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#:
private void BindGrid()
{
string conn = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conn))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Herramientas", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dtReport = new DataTable())
{
sda.Fill(dtReport);
gv_localidad.DataSource = dtReport;
gv_localidad.DataBind();
}
}
}
}
}
protected void OnEdit(object sender, EventArgs e)
{
GridViewRow row = (sender as Button).NamingContainer as GridViewRow;
int index = row.RowIndex;
for (int i = 0; i < gv_localidad.Rows.Count; i++)
{
if (index == i)
{
(gv_localidad.Rows[i].FindControl("btnUpdate") as Button).Visible = true;
(gv_localidad.Rows[i].FindControl("btnEdit") as Button).Visible = false;
}
else
{
(gv_localidad.Rows[i].FindControl("btnEdit") as Button).Visible = false;
}
}
}
The reason why i ask is because the buttons doesnt even appear. If you wanna see the full class pls tell me, thanks.

Paging in nested gridview webforms

I am having a little trouble with paging in a nested grid view.
When I try to change page I am getting some very strange and unexpected behaviour. Sometimes it will post back but not actually change the page and sometimes it does change the page but not as expected, it is messing with the order so you will have some items from the previous page still.
My markup is as follows:
<asp:GridView
ID="grdImages"
runat="server"
AllowPaging="true"
ShowFooter="true"
PageSize="5"
AutoGenerateColumns="false"
OnPageIndexChanging="grdImages_PageIndexChanging"
OnRowCancelingEdit="grdImages_RowCancelingEdit"
OnRowCommand="grdImages_RowCommand"
OnRowEditing="grdImages_RowEditing"
OnRowUpdating="grdImages_RowUpdating"
OnRowDeleting="grdImages_RowDeleting"
EmptyDataText="No Data Available at this Time"
OnRowDataBound="grdImages_RowDataBound"
DataKeyNames="ProductId">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField AccessibleHeaderText="Product ID" HeaderText="Product ID" FooterText="Product ID">
<ItemTemplate>
<asp:Label ID="lblProdId" runat="server" Text='<%# Eval("ProductId") %>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdId" runat="server" AppendDataBoundItems="true" >
<asp:ListItem>Select a product</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Product Main Image" FooterText="Product Main Image" HeaderText="Product Main Image">
<ItemTemplate>
<asp:Label ID="lblMainImgId" runat="server" Text='<%# Eval("ImageId") %>' ></asp:Label>
<asp:Label ID="lblMainImgName" runat="server" Text='<%# Eval("ImageName") %>' ></asp:Label> <br />
<asp:Image ID="imgMain" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="flupEditMain" runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupMain" runat="server" AllowMultiple="false" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Supporting Images" FooterText="Supporting Images" HeaderText="Supporting Images">
<ItemTemplate>
<asp:GridView ID="grdSupImages"
runat="server" ShowHeader="false" CellPadding="4"
ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"
OnRowEditing="grdSupImages_RowEditing"
OnRowUpdating="grdSupImages_RowUpdating" AllowPaging="true" PageSize="4"
OnPageIndexChanging="grdSupImages_PageIndexChanging" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="imgSupId" runat="server" Text='<%# Eval("ImgId") %>' ></asp:Label>
<asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:Label ID="imgSupName" runat="server" Text='<%# Eval("ImageName") %>' AssociatedControlID="imgSup"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:CheckBox ID="chkSupImages" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupExtra" runat="server" AllowMultiple="true" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<br />
<span onclick="return confirm('Are you sure you want to delete these images?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<br />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
My code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.IO;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class Admin_ProductManagement_addProdImage : System.Web.UI.Page
{
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
private string imageDirectory;
protected void Page_Load(object sender, EventArgs e)
{
// ensure images are uploaded to the right folder.
imageDirectory = Path.Combine(
Request.PhysicalApplicationPath, #"Images\ProductImages");
if (!this.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
// define ado.net objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "DisplayMain";
try
{
con.Open(); // try to open the connection
DataSet ds = new DataSet(); // Initializes a new instance of the DataSet class
adapter.Fill(ds, "ProductImages"); // Adds or refreshes rows in the DataSet to match those in the data source using the DataSet and DataTable names
grdImages.DataSource = ds; // sets the gridview datasource
grdImages.DataBind(); // binds data to gridview
// find dropdownlist in the footer row of the gridview
DropDownList prods = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId");
// call function
lstProducts(prods);
}
catch (Exception err)
{
lblGrdImages.Text = "BindGrid error: " + err.Message + err.Source + err.StackTrace; // display exceptions in label
}
finally
{
con.Close(); // close connection, even if action was unsuccessful.
}
}
protected void BindNestedGrid(int product, GridView grd)
{
// define ado.net objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "DisplayExtra";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = product;
// try to connect, fill dataset and close connection. Also catch exceptions.
try
{
con.Open(); // open the connection.
DataSet rds = new DataSet(); // initialize a data set.
adapt.Fill(rds, "ExtraImages"); // fills dataset
grd.DataSource = rds; // assign data source.
grd.DataBind(); // bind data.
}
catch (Exception err)
{
lblGrdImages.Text = "Bind Nested Grid Error: " + err.Message; // catch exceptions.
}
finally
{
con.Close(); // close the db connection
}
}
protected void lstProducts(DropDownList prods)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader;
// define the sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "LstProds";
try
{
con.Open(); // try to connect to db.
reader = cmd.ExecuteReader(); // execut the reader
while (reader.Read())
{
ListItem item = new ListItem(); // create listitem
item.Text = reader["ProductName"].ToString(); // add product name to item text
item.Value = reader["ProductId"].ToString(); // add productId to item value
prods.Items.Add(item); // populate dropdown list.
}
}
catch (Exception err)
{
lblGrdImages.Text = "List Products Error: " + err.Message; // display error message in a label
}
finally
{
con.Close(); // close the connection.
}
}
protected void addMain(int ProdId, string ImgName, string ImgPath)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "AddMain";
cmd.Parameters.Add(new SqlParameter("#ImageName", SqlDbType.VarChar, 50));
cmd.Parameters["#ImageName"].Value = ImgName;
cmd.Parameters.Add(new SqlParameter("#ImagePath", SqlDbType.VarChar, -1));
cmd.Parameters["#ImagePath"].Value = ImgPath;
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = ProdId;
try
{
con.Open(); // attempt to open the connection
DataSet ds = new DataSet(); // initialize the dataset
adapter.Fill(ds, "ProductImages"); // fill the data set.
}
catch (Exception err)
{
lblGrdImages.Text = "Add main error: " + err.Message; // display exceptions in a label control
}
finally
{
con.Close(); // close connection.
}
}
protected void addExtraImages(int ProductId, string ExImgName, string ExImagePath)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "AddExtra";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = ProductId;
cmd.Parameters.Add(new SqlParameter("#ImageName", SqlDbType.VarChar,50));
cmd.Parameters["#ImageName"].Value = ExImgName;
cmd.Parameters.Add(new SqlParameter("#ImagePath", SqlDbType.VarChar,-1));
cmd.Parameters["#ImagePath"].Value = ExImagePath;
try
{
con.Open(); // try to open db connection
DataSet ds = new DataSet(); // initialize data set.
adapter.Fill(ds, "ProductImages"); // fill the data set.
}
catch (Exception err)
{
lblGrdImages.Text = "Add extra images error: " + err.Message; // display exception in a label
}
finally
{
con.Close(); // close the connection
}
}
protected void DeleteProductImages(int Product)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "Delete";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = Product;
try
{
con.Open(); // open connection
DataSet ds = new DataSet(); // initialize rthe dataset
adapter.Fill(ds); // fill dataset.
}
catch (Exception err)
{
lblGrdImages.Text = "Delete error: " + err.Message; // report error in a label.
}
finally
{
con.Close(); // close the connection.
}
}
protected void grdImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdImages.PageIndex = e.NewPageIndex; // sets the page index
BindGrid(); // bind the grid.
}
protected void grdImages_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdImages.EditIndex = -1; // sets the page index
BindGrid(); // bind the grid.
}
private bool isValid(HttpPostedFile file, string[] extAry, string ext) // checks extension
{
bool isValid = false;
for (int i = 0; i < extAry.Length; i++)
{
if (ext.ToLowerInvariant().IndexOf(extAry[i]) > -1)
isValid = true;
}
return isValid;
}
protected void uploadMainImage() {
string[] validFileTypes = { ".jpg", ".png" }; // file type array
FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain"); // find control
DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId"); // find control
string mainFile = Path.GetFileName(main.PostedFile.FileName); // get file name.
string ext = Path.GetExtension(mainFile); // get file extension.
if (isValid(main.PostedFile, validFileTypes, ext)) // check if file extension is valid.
{
if (File.Exists(mainFile)) // check if file exists
{
lblGrdImages.Text = "File with the name: " + mainFile + " already exists. Please rename or choose a different file.";
}
else
{
try
{
string serverFileName = Path.GetFileName(mainFile); // assign values to variables
string uploadPath = Path.Combine(imageDirectory, serverFileName);
int Product = Convert.ToInt32(products.SelectedValue);
main.SaveAs(uploadPath); // save file
addMain(Product, serverFileName, #"~\Images\ProductImages\" + serverFileName); // Call stored procedure
}
catch (Exception err)
{
lblGrdImages.Text = err.Message;
}
}
}
}
protected void uploadExtraImages()
{
string[] validFileTypes = { ".jpg", ".png" }; // file type array
FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra"); // find conrol
DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId"); // find control
if (extra.HasFiles)
{
foreach (HttpPostedFile file in extra.PostedFiles)
{
string ext = Path.GetExtension(file.FileName);
if (isValid(file, validFileTypes, ext)) // check file extension
{
string serverFileName = Path.GetFileName(file.FileName); // assign values to variables
string uploadPath = Path.Combine(imageDirectory, serverFileName);
int Product = Convert.ToInt32(products.SelectedValue);
try
{
file.SaveAs(uploadPath); // save file
addExtraImages(Product, serverFileName, #"~\Images\ProductImages\" + serverFileName); // call stored procedure
}
catch (Exception err)
{
lblGrdImages.Text = "Error: " + err.Message;
}
}
}
}
}
protected void grdImages_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
// find the required controls in the grdview.
FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain");
FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra");
if (main.HasFile)
{
uploadMainImage();
if (extra.HasFiles)
{
uploadExtraImages();
}
grdImages.EditIndex = -1;
BindGrid();
}
else
{
lblGrdImages.Text = "Product main image is required.";
}
}
}
protected void grdImages_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (!this.IsPostBack)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView grd = (GridView)e.Row.FindControl("grdSupImages"); // find controls
Label prodId = (Label)e.Row.FindControl("lblProdId");
int product = Convert.ToInt32(prodId.Text); // assign values to variables.
BindNestedGrid(product, grd); // call the function.
}
}
}
protected void grdImages_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// find controls
Label product = (Label)grdImages.Rows[e.RowIndex].FindControl("lblProdId");
Label image = (Label)grdImages.Rows[e.RowIndex].FindControl("lblMainImgName");
GridView grd = (GridView)grdImages.Rows[e.RowIndex].FindControl("grdSupImages");
// declare variables and assign values
int prodid = Convert.ToInt32(product.Text);
string path = Server.MapPath(#"~\Images\ProductImages\" + image.Text);
File.Delete(path);
foreach(GridViewRow row in grd.Rows)
{
Label img = (Label)row.FindControl("imgSupName");
string imgName = img.Text;
string imgPath = Server.MapPath(#"~\Images\ProductImages\" + imgName);
try
{
File.Delete(imgPath);
}
catch (Exception err)
{
lblGrdImages.Text = "File Delete Error: " + err.Message + "<br />" + err.InnerException + "||" + err.StackTrace;
}
}
DeleteProductImages(prodid);
grdImages.EditIndex = -1;
BindGrid();
}
protected void grdImages_RowEditing(object sender, GridViewEditEventArgs e)
{
grdImages.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void grdImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void grdSupImages_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void grdSupImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
}
}
I would be eternally grateful of any assistance with this matter. If you require any further information please let me know and I will provide.
Although nobody wanted to help me, I have found the answer to my problem.
I thought id share this information as it may be able to help somebody else.
This is what I came up with for my child gridview pageindexchanging event:
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
BindNestedGrid(Convert.ToInt32(gv.ToolTip), gv);
}

asp.net - Server validation does not fire on first submission

I'm having the issue with my Custom Validator using the OnServerValidation. It does not fire when I first submit, but correctly fires afterwards.
In other words, even if I do not fill the data in my text field correctly and submit the first time around, the Validator does not catch the mistake and still accepts the data the field contains, but when I return the form, it then catches the inconsistency second time I submit.
I have 3 validators that validate this field. The other two validators work fine, its only the OnServer validation that is faulty.
My sample ASP Code is for editing is:
<asp:TemplateField HeaderText="End Date" SortExpression="end_date">
<EditItemTemplate>
<asp:TextBox ID="txtEndDate" runat="server" Text='<%# Bind("End_Date", "{0:MM/dd/yyyy}") %>'></asp:TextBox>
<asp:Image ID="imgEndDt" runat="server" ImageUrl="images/calendar.png" ImageAlign="Middle" />
<asp:Label ID="hvEndDate" runat="server" Text="?" ToolTip="blah" BackColor="#507CD1" ForeColor="White" Font-Bold="True" Height="15" Font-Underline="True"></asp:Label>
<asp:RegularExpressionValidator ID="revEndDate" runat="server"ErrorMessage="RegularExpressionValidator" ControlToValidate="txtEndDate" Text="(mm/dd/yyyy), ex: 06/03/2011." ValidationExpression="([1-9]|0[1-9]|1[012])[- /.]([1-9]|0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d"></asp:RegularExpressionValidator>
<cc1:CalendarExtender ID="ceTestDt5" runat="server" TargetControlID="txtEndDate" PopupButtonID="imgEndDt"></cc1:CalendarExtender><br />
<asp:CustomValidator ID="cvEndDate" runat="server" ErrorMessage="blah" ControlToValidate="txtEndDate" ValidateEmptyText="True" ClientValidationFunction="currentDt"></asp:CustomValidator>
<br /><asp:CustomValidator ID="cvExitDateCred" runat="server" ErrorMessage="blah" OnServerValidate="exitDateCheck_server" ControlToValidate="txtEndDate"></asp:CustomValidator>
</EditItemTemplate>
And my Code behind CS code is:
protected void exitDateCheck_server(object obj, ServerValidateEventArgs args)
{
args.IsValid = true;
Boolean hasCredEndDate = false;
String personExit = String.Empty;
if (dvPerson.FindControl("txtEndDate") != null)
{
personExit = (dvPerson.FindControl("txtEndDate") as TextBox).Text.Trim();
if (personExit != String.Empty)
{
try
{
SqlDataReader rdr = null;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("blah", con);
cmd.Parameters.Add("blah", SqlDbType.VarChar).Value = txtPPersonId.Text;
con.Open();
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
if (Int32.Parse(rdr["cnt"].ToString()) > 0)
{
hasCredEndDate = true;
}
}
cmd.Dispose();
con.Close();
if (hasCredEndDate == true)
{
args.IsValid = false;
SqlDataReader rdr2 = null;
SqlConnection con2 = new SqlConnection(constr);
SqlCommand cmd2 = new SqlCommand("blah, con2);
cmd2.Parameters.Add("blah", SqlDbType.VarChar).Value = txtPPersonId.Text;
cmd2.Parameters.Add("blah", SqlDbType.VarChar).Value = (dvPerson.FindControl("txtEndDate") as TextBox).Text;
con2.Open();
rdr2 = cmd2.ExecuteReader();
if (rdr2.Read())
{
if (Int32.Parse(rdr2["cnt"].ToString()) > 0)
{
args.IsValid = true;
}
}
cmd2.Dispose();
con2.Close();
}
}
catch (Exception e)
{
lblMessage.Text = e.ToString();
}
}
}
}
I apologize if I am leaving out any necessary information, I will add if needed.

Get number of rows deleted using checkbox in gridview

here i want to have no.of coloumns i have checked and deleted in lable
i have used following code to execute my query of deleting multiple values in gridview using checkbox
here is my code and script part
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
grd_bnd();
}
}
private void grd_bnd()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from student", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void Button3_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox1 = (CheckBox)row.FindControl("checkboxdelete");
if (checkbox1.Checked)
{
int rollno = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString());
//CheckBox checkbox1 = (CheckBox)row.FindControl("checkbox1");
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("delete from student where rollno = #rollno ", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#rollno", SqlDbType.Int).Value = rollno.ToString();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
}
}
grd_bnd();
}
}
and here is script
<asp:GridView ID="GridView1" runat="server" DataKeyNames="rollno" AllowSorting="true" AutoGenerateColumns="False" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" >
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="checkboxdelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblname" runat ="server" Text='<%#Eval("name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Roll No.">
<ItemTemplate>
<asp:Label ID="lblrollno" runat ="server" Text='<%#Eval("rollno") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Batch">
<ItemTemplate>
<asp:Label ID="lblbatch" runat ="server" Text='<%#Eval("batch") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Course">
<ItemTemplate>
<asp:Label ID="lblcourse" runat ="server" Text='<%#Eval("course") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</gridview>
<asp:Button ID="Button3" runat="server" Font-Bold="True" Text="Delete Selected" ForeColor="#000066" OnClick="Button3_Click" />
<asp:Label ID="Label1" runat="server" ForeColor="#666666"></asp:Label>
i wanna get the number of entities deleted in above lable , lable1.
Simply add a count before your loop
protected void Button3_Click(object sender, EventArgs e)
{
int rows = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox1 = (CheckBox)row.FindControl("checkboxdelete");
if (checkbox1.Checked)
{
int rollno = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString());
//CheckBox checkbox1 = (CheckBox)row.FindControl("checkbox1");
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("delete from student where rollno = #rollno ", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#rollno", SqlDbType.Int).Value = rollno.ToString();
con.Open();
rows += cmd.ExecuteNonQuery(); //Can return 0 if no rows were deleted!
con.Close();
cmd.Dispose();
}
}
grd_bnd();
MessageBox.Show(String.Format("Rows affected {0}", rows);
}
You can use the return value of ExecuteNonQuery:
int numDeleted = cmd.ExecuteNonQuery();
MSDN: returns the number of rows affected.
If you want the total rows use a variable:
int totalNumDeleted = 0;
foreach (GridViewRow row in GridView1.Rows)
{
// ...
int numDeleted = cmd.ExecuteNonQuery();
totalNumDeleted += numDeleted;
}
Label1.Text = string.Format("{0} students were deleted successfully.", totalNumDeleted);

Insert the data when user click on select button inside the gridview

I have a gridview as below
<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" AllowSorting="True"
OnSelectedIndexChanged="gvDoctorList_SelectedIndexChanged" OnRowCommand="gvDoctorList_RowCommand" OnRowDataBound="gvDoctorList_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%--<asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged" AutoPostBack="true" />--%>
<asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'></asp:Label>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandArgument='<%# Eval("PatientId") %>' CommandName = "Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PatientId" HeaderText="PatientId" SortExpression="PatientId" />
<asp:BoundField DataField="firstname" HeaderText="firstname" SortExpression="firstname" />
<asp:BoundField DataField="lastname" HeaderText="lastname" SortExpression="lastname" />
<asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>"
SelectCommand="SELECT [PatientId],[firstname], [lastname], [sex] FROM [PatientDetails]"></asp:SqlDataSource>
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" />
Code behind gridview rowcommand is as below
protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int pID = Convert.ToInt32(e.CommandArgument);
Session["PatientId"] = Convert.ToString(e.CommandArgument);
//Server.Transfer("Patientstaticformatrix.aspx");
string pIDstr = Convert.ToString(Session["PatientId"]);
if (!string.IsNullOrEmpty(pIDstr))
{
int patientID = Convert.ToInt32(pID);
//string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
string sqlquery = "SELECT * FROM [MyDatabase].[dbo].[PatExam] where PId = '" + patientID + "'";
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using(SqlConnection conn = new SqlConnection(connection))
{
//SqlConnection conn = new SqlConnection(con);
DataSet ds;
ds = new DataSet();
SqlDataAdapter cmpatientexam;
conn.Open();
cmpatientexam = new SqlDataAdapter(sqlquery, conn);
cmpatientexam.Fill(ds, "PatientExam");
TreeNode pidnode = new TreeNode();
pidnode.Text = pIDstr;
foreach (DataRow patrow in ds.Tables["PatientExam"].Rows)
{
//TreeNode tvpatexam = new TreeNode();
//tvpatexam.Text = patrow["PId"].ToString();
//TreeView1.Nodes.Add(tvpatexam);
//for (int i = 0; i < ds.Tables["PatientExam"].Columns["PId"].Count; i++)
//if (patrow["PId"].ToString() != DBNull.Value)
//{
TreeNode childtvpatexam = new TreeNode();
childtvpatexam.Text = patrow["Exam"].ToString();
pidnode.ChildNodes.Add(childtvpatexam);
//break;
//}
//TreeView1.Nodes.Add(tvpatexam);
}
TreeView1.Nodes.Add(pidnode);
ds.Dispose();
cmpatientexam.Dispose();
conn.Close();
conn.Dispose();
}
}
}
}
Code behind the button click event is as below
protected void btnformatric_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvDoctorList.Rows)
{
Button btn = (Button)row.FindControl("Select");
if (btn != null)
{
string pIDstr = Convert.ToString(Session["PatientId"]);
string exam = ((Button)sender).Text;
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PatExam]([PId],[Exam]) VALUES (#pid,#exam)", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#pid", pIDstr);
cmd.Parameters.AddWithValue("#exam", exam);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write("Error Occured: " + ex.Message.ToString());
}
finally
{
con.Close();
cmd.Dispose();
}
}
}
}
I want to insert the value which is selected from gridview using select button and insert that selected value on button click event....but with the above code it is not working...
Can anyone suggest me some other idea or if possible with these code then how...can you give me the code for it....Thanks a lot
You can add a hidden field and save Gridview's rowindex in the hidden field. In btnformatric_Click you can get the row by index and get the data. The markup:
<asp:HiddenField ID="hdnRowIndex" runat="server" Value ="" />
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" />
In code, gvDoctorList_RowCommand method:
protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int pID = Convert.ToInt32(e.CommandArgument);
Session["PatientId"] = Convert.ToString(e.CommandArgument);
//Server.Transfer("Patientstaticformatrix.aspx");
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
hdnRowIndex.Value = gvr.RowIndex.ToString();
... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
btnformatric_Click method:
protected void btnformatric_Click(object sender, EventArgs e)
{
int rowIndex = 0;
if (int.TryParse(hdnRowIndex.Value, out rowIndex))
{
//Get the row
GridViewRow row = gvDoctorList.Rows[rowIndex];
Button btn = (Button)row.FindControl("Select");
if (btn != null)
{
string pIDstr = Convert.ToString(Session["PatientId"]);
string exam = ((Button)sender).Text;
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PatExam]([PId],[Exam]) VALUES (#pid,#exam)", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#pid", pIDstr);
cmd.Parameters.AddWithValue("#exam", exam);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write("Error Occured: " + ex.Message.ToString());
}
finally
{
con.Close();
cmd.Dispose();
}
}
}
}
I presume that you're interested in inserting a record based on the selected PatientID value from the GridView?
What you want to do is start by setting the GridView's DataKeyNames property to PatientID like so:
<asp:GridView ID="gvDoctorList" runat="server" DataKeyNames="PatientID" ...>
Then in the btnformatric_Click event handler you can get the selected PatientID value via gvDoctorList.SelectedValue, as in:
string pIDstr = gvDoctorList.SelectedValue.ToString();
Of course, before you do the above you should check to make sure that the user has selected a patient from the grid (namely, that gvDoctorList.SelectedIndex >= 0).

Categories