I have a grid view control in my page that indexes all the Lecture Contents. I have added a Text Box control and a Link Button. But for the Lectures that have no Content yet, the Grid View does not appear.
Have tried many references, as a result the footer has appeared but I am not able to insert data using the Controls in the footer.
My main objective is to make the Controls behave same in both scenarios.
Here is the Grid View Code.
`<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EmptyDataText="No Contents found for this lecture." ShowFooter="true" HeaderStyle-Wrap="false" Width="70%" CssClass="Grid" AlternatingRowStyle-CssClass="alt" PagerStyle-CssClass="pgr" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText=" LectureID " SortExpression="lecc_id">
<ItemTemplate>
<asp:Label ID="lbllecc_id" runat="server" Text='<%# Bind("lecc_id") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lbllecc_id" runat="server" T`enter code here`ext="Create New">
</asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Content " SortExpression="lecc_contents">
<EditItemTemplate>
<asp:TextBox ID="tblecc_contents" runat="server" Text='<%# Bind("lecc_contents") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbllecc_contents" runat="server" Text='<%# Bind("lecc_contents") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtcontent" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfcontent" runat="server" ErrorMessage="Content field cannot be blank." ControlToValidate="txtcontent" Text="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:LinkButton ID="createcontent" runat="server" OnClick="createcontent" CssClass="btn-sm btn-default">Insert Content</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</EmptyDataTemplate>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" Font-Size="17px" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" Font-Bold="False" Font-Size="14px" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>`
and the code behind functions for grid view.
`protected void Page_Load(object sender, EventArgs e){
if (Session["fac_username"] != null)
{
String username = Convert.ToString(Session["fac_username"]);
if (!IsPostBack)
{
BindGridViewData();
}
}
else
{
Response.Redirect("~/Account/Login.aspx");
}
}protected void BindGridViewData(){
int lecID = Convert.ToInt32(Session["lecID"]);
GridView1.DataSource = DataAccessLayer.getAllContents(lecID);
GridView1.DataBind();} protected void GridView1_SelectedIndexChanged(object sender, EventArgs e){
}
protected void createcontent(object sender, EventArgs e){
int lecID = Convert.ToInt32(Session["lecID"]);
con.Open();
SqlCommand command = new SqlCommand("insert into uni_lect_content(lecc_id, lecc_contents) values(#lecc_id, #lecc_contents)", con);
command.Parameters.AddWithValue("#lecc_id", lecID);
command.Parameters.AddWithValue("#lecc_contents", ((TextBox)GridView1.FooterRow.FindControl("txtcontent")).Text);
command.ExecuteNonQuery();
con.Close();
lblmsg.Text = "New Course Successfully Created..!";}`
DataAccessLayer class's getAllConents() method is here.
`public class AllContents
{
public long lecc_id { get; set; }
public string lecc_contents { get; set; }
}
public class DataAccessLayer
{
public static List<AllContents> getAllContents( int lecID){
List<AllContents> listAll = new List<AllContents>();
string cs = ConfigurationManager.ConnectionStrings["ILMSConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand com = new SqlCommand("select lecc_id, lecc_contents from uni_lect_content, uni_lectures, uni_offered_courses where uni_lect_content.lecc_id = uni_lectures.lec_id and uni_lectures.cours_offer_id = uni_offered_courses.cours_offer_id and lecc_id = '"+lecID+"'", con);
con.Open();
SqlDataReader rdr = com.ExecuteReader();
while (rdr.Read())
{
AllContents obj = new AllContents();
obj.lecc_id = Convert.ToInt32(rdr["lecc_id"]);
obj.lecc_contents = rdr["lecc_contents"].ToString();
listAll.Add(obj);
}
}
return listAll;
}`
Help me out of this situation.
Thanks in advance.
FRONT END GRDIVIEW
<asp:GridView ID="grdview" ShowFooter="true" OnRowEditing="grdview_RowEditing" OnRowCancelingEdit="grdview_RowCancelingEdit" OnRowCommand="grdview_RowCommand" OnRowUpdating="grdview_RowUpdating" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="SR No.">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
<asp:Label ID="lblid" runat="server" Text='<%#Eval("Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Emp Name">
<ItemTemplate>
<asp:Label ID="elblempname" runat="server" Text='<%#Eval("EmpName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempname" runat="server" Text='<%#Eval("EmpName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempname" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Emp No">
<ItemTemplate>
<asp:Label ID="elblempno" runat="server" Text='<%#Eval("EmpNo") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempno" runat="server" Text='<%#Eval("EmpNo") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempno" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Email">
<ItemTemplate>
<asp:Label ID="elblempemail" runat="server" Text='<%#Eval("Email_Id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempemail" runat="server" Text='<%#Eval("Email_Id") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempemail" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Age">
<ItemTemplate>
<asp:Label ID="elblempage" runat="server" Text='<%#Eval("Age") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempage" runat="server" Text='<%#Eval("Age") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempage" runat="server" ></asp:TextBox>
<asp:Button ID="btnAdd" CommandName="AddNew" runat="server" Text="Add" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
BACKEND CODE
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
grdview.DataSource = ds;
grdview.DataBind();
int columncount = grdview.Rows[0].Cells.Count;
grdview.Rows[0].Cells.Clear();
grdview.Rows[0].Cells.Add(new TableCell());
grdview.Rows[0].Cells[0].ColumnSpan = columncount;
grdview.Rows[0].Cells[0].Text = "No Records Found";
if (e.CommandName == "AddNew")
{
TextBox ftxtempname = (TextBox)grdview.FooterRow.FindControl("ftxtempname");
TextBox ftxtempno = (TextBox)grdview.FooterRow.FindControl("ftxtempno");
TextBox ftxtempemail = (TextBox)grdview.FooterRow.FindControl("ftxtempemail");
TextBox ftxtempage = (TextBox)grdview.FooterRow.FindControl("ftxtempage");
using (con)
{
SqlCommand cmd = new SqlCommand("usp_add_upd_emptb", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpName", ftxtempname.Text);
cmd.Parameters.AddWithValue("#EmpNo", ftxtempno.Text);
cmd.Parameters.AddWithValue("#Desig", ftxtempage.Text);
cmd.Parameters.AddWithValue("#Email", ftxtempemail.Text);
con.Open();
cmd.ExecuteNonQuery();
}
This is a working complete code.
I have a details view and a button, and when I click on the button, I want to check if the username is already in the database or not. I tried the below code but it goes to the else statement, even if the username exists.
Any help?
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string query = "select Username from [Login]";
SqlCommand cmd = new SqlCommand(query);
SqlDataAdapter sqlda = new SqlDataAdapter(cmd.CommandText, con);
DataTable dt = new DataTable();
sqlda.Fill(dt);
int RowCount = dt.Rows.Count;
for (int i = 0; i < RowCount; i++)
{
Label13.Text = ((TextBox)DetailsView1.FindControl("TextBox1")).Text;
Label14.Text = dt.Rows[i]["Username"].ToString();
if (Label13.Text == Label14.Text)
{
string message = "Username is Already Exists";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
else
{
string message = "Successfully saved";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
}
}
Details view markup:
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
CellPadding="4" DataKeyNames="Username" DataSourceID="SqlDataSource3"
ForeColor="#333333" GridLines="None" Height="50px" Width="283px"
style="margin-top: 0px; text-align: left;"
onitemupdated="DetailsView1_ItemUpdated" onitemdeleted="DetailsView1_ItemDeleted"
oniteminserted="DetailsView1_ItemInserted" DefaultMode="Insert"
oniteminserting="DetailsView1_ItemInserting">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
<EditRowStyle BackColor="#999999" />
<FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
<Fields>
<asp:TemplateField HeaderText="Username" SortExpression="Username">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Username") %>'></asp:Label>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Username") %>'
ValidationGroup="1"></asp:TextBox>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server"
ErrorMessage="*" ControlToValidate="TextBox1" ForeColor="Red"
ValidationGroup="1"></asp:RequiredFieldValidator>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Password" SortExpression="Password">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Password") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Password") %>' ValidationGroup="1"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="TextBox2" ErrorMessage="*" ForeColor="Red"
ValidationGroup="1"></asp:RequiredFieldValidator>
</InsertItemTemplate>
<ItemTemplate>
</ItemTemplate>
<ControlStyle />
</asp:TemplateField>
<asp:TemplateField HeaderText="UserType" SortExpression="UserType">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("UserType") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="DropDownList4" runat="server"
ConnectionString ="<%$ConnectionStrings: ConnectionString %>"
SelectedValue='<%# Bind("UserType") %>' ValidationGroup="1">
<asp:ListItem>--Select--</asp:ListItem>
<asp:ListItem>employee</asp:ListItem>
<asp:ListItem>doctor</asp:ListItem>
<asp:ListItem>student</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="DropDownList4" ErrorMessage="*" ForeColor="Red"
InitialValue="--Select--" ValidationGroup="1"></asp:RequiredFieldValidator>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("UserType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Button" ShowInsertButton="True" ValidationGroup="1" />
</Fields>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
</asp:DetailsView>
Why don't you pass username as parameter to Db.
string query = "select Username from [Login] where Username=#username";
var nameParam = new SqlParameter("username");
nameParam.Value = Label13.Text;
cmd.Parameters.Add(nameParam);
It will fetch only records if username will exist in db.
Then Check it using rowCount.
if(RowCount> 0){
//Username exist
}else {
//Do other work
}
Can you please try this way.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string query = "select Username from [Login] WHERE Username='"+((TextBox)DetailsView1.FindControl("TextBox1")).Text+"'";
SqlCommand cmd = new SqlCommand(query);
SqlDataReader reader = cmd.ExecuteReader();
if(reader.HasRows())
{
// The username exist
}
I have a database that stores lottery form submissions from users. One of the columns is a DateTime column that is populated with the current DateTime every time someone submits a form. I want to be able to search by the DateTime column so I can pull up all the forms entered on a particular day.
I'm not getting any errors when I perform the search, just my custom message that "No results matching that search criteria". I've tried disabling the jquery datepicker and tried copying and pasting the exact DateTime field from the DB into the search box and still nothing. Obviously I'm missing something but I can't figure out what. Any help is much appreciated.
C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class adminDefault : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void lastNameButton(object sender, EventArgs e)
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["10thLottoApp"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT First, Last, Addr1, C, S, Z, dayphone, eveningphone, email, tripCC, tripCCexpiration, tripCVV, tripCCname, memberCC, memberCCexpiration, memberCVV, memberCCname, membership, hutCredit, creditName, GroupName, Id, LotteryChoices, dateTime FROM Lotto WHERE Last LIKE '%'+ #Name + '%'", conn);
comm.Parameters.Add("#Name", System.Data.SqlDbType.NVarChar, 50).Value = nameSearch.Text;
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
if (!reader.HasRows)
{
noMatchLabel.Text = "No results matching that search criteria.";
}
else
{
grid.DataSource = reader;
grid.DataKeyNames = new string[] { "Id" };
grid.DataBind();
reader.Close();
conn.Close();
noMatchLabel.Text = null;
}
}
protected void groupNameButton(object sender, EventArgs e)
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["10thLottoApp"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT First, Last, Addr1, C, S, Z, dayphone, eveningphone, email, tripCC, tripCCexpiration, tripCVV, tripCCname, memberCC, memberCCexpiration, memberCVV, memberCCname, membership, hutCredit, creditName, GroupName, Id, LotteryChoices, dateTime FROM Lotto WHERE GroupName LIKE '%'+ #GroupName + '%'", conn);
comm.Parameters.Add("#GroupName", System.Data.SqlDbType.NVarChar, 50).Value = groupSearch.Text;
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
if (!reader.HasRows)
{
noMatchLabel.Text = "No results matching that search criteria.";
}
else
{
grid.DataSource = reader;
grid.DataKeyNames = new string[] { "Id" };
grid.DataBind();
reader.Close();
conn.Close();
noMatchLabel.Text = null;
}
}
protected void dateSearch(object sender, EventArgs e)
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["10thLottoApp"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT First, Last, Addr1, C, S, Z, dayphone, eveningphone, email, tripCC, tripCCexpiration, tripCVV, tripCCname, memberCC, memberCCexpiration, memberCVV, memberCCname, membership, hutCredit, creditName, GroupName, Id, LotteryChoices, dateTime FROM Lotto WHERE dateTime = #dateTime ", conn);
comm.Parameters.Add("#dateTime", System.Data.SqlDbType.DateTime).Value = DateTime.Parse(datesearch.Text);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
if (!reader.HasRows)
{
noMatchLabel.Text = "No results matching that search criteria.";
}
else
{
grid.DataSource = reader;
grid.DataKeyNames = new string[] { "Id" };
grid.DataBind();
reader.Close();
conn.Close();
noMatchLabel.Text = null;
}
}
protected void grid_SelectedIndexChanged(object sender, EventArgs e)
{
BindLottoDetails();
}
private void BindLottoDetails()
{
int selectedRowIndex = grid.SelectedIndex;
int lottoId = (int)grid.DataKeys[selectedRowIndex].Value;
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["10thLottoApp"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT Id, First, Last, Addr1, C, S, Z, dayphone, eveningphone, email, tripCC, tripCCexpiration, tripCVV, tripCCname, memberCC, memberCCexpiration, memberCVV, memberCCname, membership, hutCredit, creditName, GroupName, LotteryChoices, dateTime FROM Lotto WHERE Id=#Id", conn);
comm.Parameters.Add("Id", System.Data.SqlDbType.Int);
comm.Parameters["Id"].Value = lottoId;
try
{
conn.Open();
reader = comm.ExecuteReader();
lottoFormDetails.DataSource = null;
lottoFormDetails.DataSource = reader;
lottoFormDetails.DataKeyNames = new string[] { "Id" };
lottoFormDetails.DataBind();
reader.Close();
}
finally
{
conn.Close();
}
}
protected void lottoFormDetails_ModeChanging(object sender, DetailsViewModeEventArgs e)
{
lottoFormDetails.ChangeMode(e.NewMode);
BindLottoDetails();
}
protected void lottoFormDetails_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
int LottoId = (int)lottoFormDetails.DataKey.Value;
TextBox newFirstTextBox = (TextBox)lottoFormDetails.FindControl("editFirstTextBox");
TextBox newLastTextBox = (TextBox)lottoFormDetails.FindControl("editLastTextBox");
TextBox newAddr1TextBox = (TextBox)lottoFormDetails.FindControl("editAddr1TextBox");
TextBox newCityTextBox = (TextBox)lottoFormDetails.FindControl("editCityTextBox");
TextBox newStateTextBox = (TextBox)lottoFormDetails.FindControl("editStateTextBox");
TextBox newZipTextBox = (TextBox)lottoFormDetails.FindControl("editZipTextBox");
TextBox newdaytimephoneTextBox = (TextBox)lottoFormDetails.FindControl("editdaytimephoneTextBox");
TextBox neweveningphoneTextBox = (TextBox)lottoFormDetails.FindControl("editeveningphoneTextBox");
TextBox newemailTextBox = (TextBox)lottoFormDetails.FindControl("editemailTextBox");
TextBox newmembershipTextBox = (TextBox)lottoFormDetails.FindControl("editmembershipTextBox");
TextBox newhutCreditTextBox = (TextBox)lottoFormDetails.FindControl("edithutCreditTextBox");
TextBox newcreditNameTextBox = (TextBox)lottoFormDetails.FindControl("editcreditNameTextBox");
TextBox newGroupNameBox = (TextBox)lottoFormDetails.FindControl("editGroupNameTextBox");
TextBox newLotteryChoicesTextBox = (TextBox)lottoFormDetails.FindControl("editLotteryChoicesTextBox");
string newFirst = newFirstTextBox.Text;
string newLast = newLastTextBox.Text;
string newAddr1 = newAddr1TextBox.Text;
string newCity = newCityTextBox.Text;
string newState = newStateTextBox.Text;
string newZip = newZipTextBox.Text;
string newdaytimephone = newdaytimephoneTextBox.Text;
string neweveningphone = neweveningphoneTextBox.Text;
string newemail = newemailTextBox.Text;
string newmembership = newmembershipTextBox.Text;
string newhutCredit = newhutCreditTextBox.Text;
string newcreditName = newcreditNameTextBox.Text;
string newGroupName = newGroupNameBox.Text;
string newLotteryChoices = newLotteryChoicesTextBox.Text;
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["10thLottoApp"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("UpdateLotteryForm", conn);
comm.CommandType = System.Data.CommandType.StoredProcedure;
comm.Parameters.Add("Id", System.Data.SqlDbType.Int);
comm.Parameters["Id"].Value = LottoId;
comm.Parameters.Add("NewFirst", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["NewFirst"].Value = newFirst;
comm.Parameters.Add("NewLast", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["NewLast"].Value = newLast;
comm.Parameters.Add("NewAddr1", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["NewAddr1"].Value = newAddr1;
comm.Parameters.Add("NewC", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["NewC"].Value = newCity;
comm.Parameters.Add("NewS", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["NewS"].Value = newState;
comm.Parameters.Add("NewZ", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["NewZ"].Value = newZip;
comm.Parameters.Add("Newdayphone", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["Newdayphone"].Value = newdaytimephone;
comm.Parameters.Add("Neweveningphone", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["Neweveningphone"].Value = neweveningphone;
comm.Parameters.Add("Newemail", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["Newemail"].Value = newemail;
comm.Parameters.Add("Newmembership", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["Newmembership"].Value = newmembership;
comm.Parameters.Add("NewhutCredit", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["NewhutCredit"].Value = newhutCredit;
comm.Parameters.Add("NewcreditName", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["NewcreditName"].Value = newcreditName;
comm.Parameters.Add("NewGroupName", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["NewGroupName"].Value = newGroupName;
comm.Parameters.Add("NewLotteryChoices", System.Data.SqlDbType.NVarChar, -1);
comm.Parameters["NewLotteryChoices"].Value = newLotteryChoices;
try
{
conn.Open();
comm.ExecuteNonQuery();
}
finally
{
conn.Close();
}
lottoFormDetails.ChangeMode(DetailsViewMode.ReadOnly);
BindLottoDetails();
}
}
.aspx code
<%# Page Title="" Language="C#" MasterPageFile="~/admin.master" AutoEventWireup="true" CodeFile="adminDefault.aspx.cs" Theme="Blue" Inherits="adminDefault" %>
<%# Import Namespace = "System.Data.SqlClient" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js" ></script>
<script>
$(function () {
$("#<%=datesearch.ClientID%>").datepicker();
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div id="container">
<div class="row">
<div class="col-md-12">
<h2>10th Mountain Lottery App</h2>
</div>
</div>
<div class="row">
<div class="col-md-2 sidenav">
<ul>
<li>Search Forms</li>
<li>Display Full Lottery List</li>
<li>Error Filtering</li>
</ul>
</div>
<div class="col-md-10">
<p>You can use the menu below to search for individual forms</p>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<h4>Lottery Form Search</h4>
<asp:Label runat="server">Search by Last Name: <asp:TextBox id="nameSearch" runat="server"></asp:TextBox></asp:Label>
<p><asp:Button id="nameSearchButton" runat="server" Text="Search" OnClick="lastNameButton" /></p>
<asp:Label runat="server">Search by Group Name: <asp:TextBox id="groupSearch" runat="server"></asp:TextBox></asp:Label>
<p><asp:Button id="groupsearchButton" runat="server" Text="Search" OnClick="groupNameButton" /></p>
<asp:Label runat="server">Search by Date: <asp:TextBox id="datesearch" runat="server"></asp:TextBox></asp:Label>
<p><asp:Button id="dateSearchButton" runat="server" Text="Search" OnClick="dateSearch" /></p>
<asp:Label ID="noMatchLabel" runat="server"></asp:Label>
<asp:GridView id="grid" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="grid_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="First" HeaderText="First Name" />
<asp:BoundField DataField="Last" HeaderText="Last Name" />
<asp:BoundField DataField="C" HeaderText="City" />
<asp:BoundField DataField="GroupName" HeaderText="Group Name" />
<asp:ButtonField CommandName="Select" Text="Select" />
</Columns>
</asp:GridView>
<br />
<asp:DetailsView ID="lottoFormDetails" runat="server" AutoGenerateRows="False" OnItemUpdating="lottoFormDetails_ItemUpdating" OnModeChanging="lottoFormDetails_ModeChanging">
<Fields>
<asp:TemplateField HeaderText="First Name">
<EditItemTemplate>
<asp:TextBox ID="editFirstTextBox" runat="server" Text='<%# Bind("First") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertFirstTextBox" runat="server" Text='<%# Bind("First") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="FirstLabel" runat="server" Text='<%# Bind("First") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<EditItemTemplate>
<asp:TextBox ID="editLastTextBox" runat="server" Text='<%# Bind("Last") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertLastTextBox" runat="server" Text='<%# Bind("Last") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="LastLabel" runat="server" Text='<%# Bind("Last") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<EditItemTemplate>
<asp:TextBox ID="editAddr1TextBox" runat="server" Text='<%# Bind("Addr1") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertAddr1TextBox" runat="server" Text='<%# Bind("Addr1") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Addr1Label" runat="server" Text='<%# Bind("Addr1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="editCityTextBox" runat="server" Text='<%# Bind("C") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertCityTextBox" runat="server" Text='<%# Bind("C") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="CityLabel" runat="server" Text='<%# Bind("C") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="State">
<EditItemTemplate>
<asp:TextBox ID="editStateTextBox" runat="server" Text='<%# Bind("S") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertStateTextBox" runat="server" Text='<%# Bind("S") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="StateLabel" runat="server" Text='<%# Bind("S") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Zip">
<EditItemTemplate>
<asp:TextBox ID="editZipTextBox" runat="server" Text='<%# Bind("Z") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertZipTextBox" runat="server" Text='<%# Bind("Z") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="ZipLabel" runat="server" Text='<%# Bind("Z") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Daytime Phone #">
<EditItemTemplate>
<asp:TextBox ID="editdaytimephoneTextBox" runat="server" Text='<%# Bind("dayphone") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertdaytimephoneTextBox" runat="server" Text='<%# Bind("dayphone") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="daytimephoneLabel" runat="server" Text='<%# Bind("dayphone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Evening Phone #">
<EditItemTemplate>
<asp:TextBox ID="editeveningphoneTextBox" runat="server" Text='<%# Bind("eveningphone") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="inserteveningphoneTextBox" runat="server" Text='<%# Bind("eveningphone") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="eveningphoneLabel" runat="server" Text='<%# Bind("eveningphone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<EditItemTemplate>
<asp:TextBox ID="editemailTextBox" runat="server" Text='<%# Bind("email") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertemailTextBox" runat="server" Text='<%# Bind("email") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="emailLabel" runat="server" Text='<%# Bind("email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Membership">
<EditItemTemplate>
<asp:TextBox ID="editmembershipTextBox" runat="server" Text='<%# Bind("membership") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertmembershipTextBox" runat="server" Text='<%# Bind("membership") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="membershipLabel" runat="server" Text='<%# Bind("membership") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hut Credit">
<EditItemTemplate>
<asp:TextBox ID="edithutCreditTextBox" runat="server" Text='<%# Bind("hutCredit") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="inserthutCreditTextBox" runat="server" Text='<%# Bind("hutCredit") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="hutCreditLabel" runat="server" Text='<%# Bind("hutCredit") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hut Credit Name">
<EditItemTemplate>
<asp:TextBox ID="editcreditNameTextBox" runat="server" Text='<%# Bind("creditName") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertcreditNameTextBox" runat="server" Text='<%# Bind("creditName") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="creditNameLabel" runat="server" Text='<%# Bind("creditName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group Name">
<EditItemTemplate>
<asp:TextBox ID="editGroupNameTextBox" runat="server" Text='<%# Bind("GroupName") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertGroupNameTextBox" runat="server" Text='<%# Bind("GroupName") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="GroupNameLabel" runat="server" Text='<%# Bind("GroupName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lottery Choices">
<EditItemTemplate>
<asp:TextBox ID="editLotteryChoicesTextBox" TextMode="multiline" Columns="75" Rows="10" runat="server" Text='<%# Bind("LotteryChoices") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertLotteryChoicesTextBox" TextMode="multiline" Columns="75" Rows="10" runat="server" Text='<%# Bind("LotteryChoices") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="LotteryChoicesLabel" TextMode="multiline" Columns="75" Rows="10" runat="server" Text='<%# Bind("LotteryChoices") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Fields>
<HeaderTemplate>
<%#Eval("First")%> <%#Eval("Last") %> <%#Eval("dateTime") %>
</HeaderTemplate>
</asp:DetailsView>
</div>
</div>
</div>
</div>
</div>
</asp:Content
>
In SQL, you state that you are storing the data as a DateTime. This means you are getting the date and the time. Of course the time includes hours, minutes, seconds, etc...
In you query you need to CAST your DateTime to a Date in order to remove the time from it.
See this MSDN article for more clarification https://msdn.microsoft.com/en-us/library/ms187819.aspx
I've coded a gridview that doesn't fire when I click the edit button and I found an older question that addresses my issue by just using e.CommandName with if statements under the RowCommand method. I'm trying to figure out how to implement it with my code.
My question is, how do I use e.RowIndex during update to find my controls and reference those now? Also, I've tried calling my old Update method but it won't let me use sender and e as parameters because GridviewCommandEventArgs is different from GridViewEventUpdateArgs. I'm pretty lost, any help would be appreciated in straightening this out.
C#:
void RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Edit")
{
}
if (e.CommandName == "Update")
{
UpdateCustomer(sender, e);
string nFirstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtFirstName")).Text;
string nLastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLastName")).Text;
string nEmergency = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmergency")).Text;
string nCell = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCell")).Text;
string nAge = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAge")).Text;
string nActivityCard = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtActivityCard")).Text;
string nBoat = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtBoat")).Text;
string nInitials = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtInitials")).Text;
string nGroup = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtGroup")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Person set FirstName=#FirstName, LastName=#LastName, " +
"Emergency#=#Emergency, Cell#=#Cell, Age=#Age, ActivityCard=#ActivityCard, Initials=#Initials, CraftType=#Boat, Group#=#Group " +
"where Person.PersonID=#Pid;" +
"SELECT Person.PersonID, Person.FirstName AS FirstName, Person.LastName AS LastName, Person.Emergency# AS Emergency#, Person.Cell# AS Cell#, Person.Age AS Age, " +
"Person.ActivityCard AS ActivityCard, Person.CraftType AS CraftType, Person.Initials AS Initials, Person.Group# AS Group# " +
"FROM Person INNER JOIN " +
"TripSchedule ON Person.PersonID = TripSchedule.PersonID where TripSchedule.Date = #Date and " +
"TripSchedule.Time = #Time and TripSchedule.TripType = #Type order by Person.Group#;";
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = nFirstName;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = nLastName;
cmd.Parameters.Add("#Emergency", SqlDbType.NChar).Value = nEmergency;
cmd.Parameters.Add("#Cell", SqlDbType.NChar).Value = nCell;
cmd.Parameters.Add("#Age", SqlDbType.NChar).Value = nAge;
cmd.Parameters.Add("#ActivityCard", SqlDbType.NChar).Value = nActivityCard;
cmd.Parameters.Add("#Initials", SqlDbType.NChar).Value = nInitials;
cmd.Parameters.Add("#Boat", SqlDbType.VarChar).Value = nBoat;
cmd.Parameters.Add("#Group", SqlDbType.VarChar).Value = nGroup;
cmd.Parameters.AddWithValue("#Date", TextBox1.Text);
cmd.Parameters.AddWithValue("#Time", ddlTripTime.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Type", ddlTripType.SelectedItem.ToString());
long personID = long.Parse(GridView1.DataKeys[e.RowIndex].Values["PersonID"].ToString());
cmd.Parameters.AddWithValue("#Pid", personID);
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
if (e.CommandName == "Cancel")
{
}
}
ASP.NET:
<div id="dvGrid" style="padding: 0px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" DataKeyNames="PersonID" runat="server" AutoGenerateColumns="False"
Font-Names="Arial" Font-Size="10pt" AlternatingRowStyle-BackColor="blue" HeaderStyle-BackColor="aqua"
ShowFooter="true" OnRowEditing="EditCustomer" OnRowUpdating="UpdateCustomer"
OnRowCancelingEdit="CancelEdit" ShowHeaderWhenEmpty="true" Height="95px">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Height="20px" Text='<%# Eval("FirstName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width = "60px" />
<FooterTemplate>
<asp:TextBox ID="txtFirstName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%#Bind("LastName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLastName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAge" Width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Activity Card">
<ItemTemplate>
<asp:Label ID="lblActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtActivityCard" Width="50px" MaxLength="7" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cell Phone">
<ItemTemplate>
<asp:Label ID="lblCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCell" Width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emergency Phone">
<ItemTemplate>
<asp:Label ID="lblEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmergency" width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Boat Type">
<ItemTemplate>
<asp:Label ID="lblBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBoat" Width="80px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Initials">
<ItemTemplate>
<asp:Label ID="lblInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtInitials" width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group #">
<ItemTemplate>
<asp:Label ID="lblGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtGroup" MaxLength="2" Width="20px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server" CommandArgument='<%# Eval("PersonID")%>'
OnClientClick="return confirm('Are you sure you want to delete?')" Text="Delete"
OnClick="DeleteCustomer"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Submit" OnClick="AddNewCustomer" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can pass RowIndex as CommandArgument for your LinkButtons.
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update" CommandArgument='<%# Container.DataItemIndex %>'>Update</asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel" CommandArgument='<%# Container.DataItemIndex %>'>Cancel</asp:LinkButton>
</EditItemTemplate>
Which can be access from code behind. Using rowindex you can get hold of the current row and find any controls using FindControl
void RowCommand(Object sender, GridViewCommandEventArgs e)
{
int rowindex = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Update")
{
....
}
if (e.CommandName == "Cancel")
{
....
}
}
e.CommandArgument will contain the index of the row clicked, so you can access the relevant controls via
int index = Convert.ToInt32(e.CommandArgument);
GridView1.Rows[index].Controls[x];
I have a gridview that has insert, update, and delete functionality. On my update statement, I'm not sure how to set my identifier PersonID = to the currently selected identifier in the gridview that is being updated. Is there a common method that people use to achieve this functionality?
Code for Asp.net GRIDVIEW
<div id="dvGrid" style="padding: 0px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
Font-Names="Arial" Font-Size="10pt" AlternatingRowStyle-BackColor="blue" HeaderStyle-BackColor="aqua"
ShowFooter="true" OnRowEditing="EditCustomer" OnRowUpdating="UpdateCustomer"
OnRowCancelingEdit="CancelEdit" Height="95px">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Height="20px" Text='<%# Eval("FirstName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFirstName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLastName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAge" Width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Activity Card">
<ItemTemplate>
<asp:Label ID="lblActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtActivityCard" Width="50px" MaxLength="7" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cell Phone">
<ItemTemplate>
<asp:Label ID="lblCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCell" Width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emergency Phone">
<ItemTemplate>
<asp:Label ID="lblEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmergency" width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Boat Type">
<ItemTemplate>
<asp:Label ID="lblBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBoat" Width="80px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Initials">
<ItemTemplate>
<asp:Label ID="lblInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtInitials" width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group #">
<ItemTemplate>
<asp:Label ID="lblGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtGroup" MaxLength="2" Width="20px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server" CommandArgument='<%# Eval("PersonID")%>'
OnClientClick="return confirm('Are you sure you want to delete?')" Text="Delete"
OnClick="DeleteCustomer"></asp:LinkButton>
</itemtemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Submit" OnClick="AddNewCustomer" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
<HeaderStyle BackColor="Aqua" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView1" />
</Triggers>
</asp:UpdatePanel>
</div>
Method for Update:
protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
{
string nFirstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtFirstName")).Text;
string nLastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLastName")).Text;
string nEmergency = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmergency")).Text;
string nCell = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCell")).Text;
string nAge = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAge")).Text;
string nActivityCard = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtActivityCard")).Text;
string nBoat = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtBoat")).Text;
string nInitials = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtInitials")).Text;
string nGroup = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtGroup")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Person set FirstName=#FirstName, LastName=#LastName, " +
"Emergency#=#Emergency, Cell#=#Cell, Age=#Age, ActivityCard=#ActivityCard, Initials=#Initials, CraftType=#Boat, Group#=#Group " +
"where Person.PersonID=Person.PersonID;" +
"SELECT Person.PersonID, Person.FirstName AS FirstName, Person.LastName AS LastName, Person.Emergency# AS Emergency#, Person.Cell# AS Cell#, Person.Age AS Age, " +
"Person.ActivityCard AS ActivityCard, Person.CraftType AS CraftType, Person.Initials AS Initials, Person.Group# AS Group# " +
"FROM Person INNER JOIN " +
"TripSchedule ON Person.PersonID = TripSchedule.PersonID where TripSchedule.Date = #Date and " +
"TripSchedule.Time = #Time and TripSchedule.TripType = #Type order by Person.Group#;";
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = nFirstName;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = nLastName;
cmd.Parameters.Add("#Emergency", SqlDbType.NChar).Value = nEmergency;
cmd.Parameters.Add("#Cell", SqlDbType.NChar).Value = nCell;
cmd.Parameters.Add("#Age", SqlDbType.NChar).Value = nAge;
cmd.Parameters.Add("#ActivityCard", SqlDbType.NChar).Value = nActivityCard;
cmd.Parameters.Add("#Initials", SqlDbType.NChar).Value = nInitials;
cmd.Parameters.Add("#Boat", SqlDbType.VarChar).Value = nBoat;
cmd.Parameters.Add("#Group", SqlDbType.VarChar).Value = nGroup;
cmd.Parameters.AddWithValue("#Date", TextBox1.Text);
cmd.Parameters.AddWithValue("#Time", ddlTripTime.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Type", ddlTripType.SelectedItem.ToString());
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
First specify DataKeyNames="PersonID" for your gridview definition.
Here is how you get the PersonID value in your UpdateCustomer function in code behind.
protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
{
// assuming that the value of your PersonID is numeric value
long personID = long.Parse(GridView1.DataKeys[e.RowIndex].Values["PersonID"].ToString());
....
}
The personID value you can pass as an argument to your WHERE clause.
Alternatively you can declare a HiddenField in your gridview and bind PersonID which you can access in you UpdateCustomer function using FindControl method.