I am binding the data into radio buttons, but error that: DataBinding: 'System.Char' does not contain a property with the name 'ProfileRbnName'..
and my Db Table is
Profile_RbnFilter
Columns are
ID, ProfileRbnName
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetGridData();
RadioButton_Bind();
}
}
public void GetGridData()
{
DataTable tableObject = new DataTable();
string sqlstr = "select a.SID as ProfileID,a.StaffName as Name,b.Designation,a.Staffqualification as Qualification,a.Uploadphoto as ImageUrl,case a.Status when '1' then 'Active' when '2' then 'InActive' end as Status,convert(varchar(12),a.date,101) as Date from Adding_New_Staff a join Dental_Designation b on a.StaffDesignation=b.Did order by a.sid";
tableObject = DAL.getData(sqlstr);
GridProfile.DataSource = tableObject;
GridProfile.DataBind();
}
private void RadioButton_Bind()
{
string cmdstr = "select ID,ProfileRbnName from Profile_RbnFilter";
DataSet ds = new DataSet();
SqlDataAdapter adp = new SqlDataAdapter(cmdstr, con);
adp.Fill(ds);
RbnFilter.DataSource = cmdstr;
RbnFilter.DataValueField = "ID";
RbnFilter.DataTextField = "ProfileRbnName";
RbnFilter.DataBind();
}
[<span style="font-size: 14px; font-weight: normal;">
<asp:RadioButtonList ID="RbnFilter" runat="server"
RepeatDirection="Horizontal" OnSelectedIndexChanged="rbnSearchby_SelectedIndexChanged"
RepeatLayout="Flow" AutoPostBack="True">
<asp:ListItem Text="All" Value="10" Selected="true" />
<asp:ListItem Text="Doctors" Value="11" />
<asp:ListItem Text="Dental Hygienist & Assistants" Value="12" />
<asp:ListItem Text="Nurses" Value="13" />
<asp:ListItem Text="Front Office" Value="14" />
</asp:RadioButtonList>
</span>]
</h1>
</div>
<div>
<asp:GridView ID="GridProfile" runat="server" AutoGenerateColumns="False"
Width="100%" ShowHeaderWhenEmpty="True" class="Grid">
<Columns>
<asp:TemplateField HeaderText="Profile ID">
<ItemTemplate>
<asp:Label ID="lblProfileID" runat="server" Text='<%# Eval("ProfileID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<ItemTemplate>
<asp:Label ID="lblDesignation" runat="server" Text='<%# Eval("Designation") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Qualification">
<ItemTemplate>
<asp:Label ID="lblQualification" runat="server" Text='<%# Eval("Qualification") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image Url">
<ItemTemplate>
<asp:Label ID="lblImageUrl" runat="server" Text='<%# Eval("ImageUrl") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" Text='<%# Eval("Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:Label ID="lbldate" runat="server" Text='<%# Eval("Date") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
private void RadioButton_Bind()
{ cmdstr = "select ID,ProfileRbnName from Profile_RbnFilter";
DataSet ds = new DataSet();
SqlDataAdapter adp = new SqlDataAdapter(cmdstr, con);
adp.Fill(ds);
RbnFilter.DataSource = ds.Tables[0];
RbnFilter.DataValueField = "ID";
RbnFilter.DataTextField = "ProfileRbnName";
RbnFilter.DataBind();
};
Related
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.
I have a grid view it has 3 drop down lists and 3 text boxes in template field. On the top of the grid view i have two text boxes( text box 1 and 2) which initilize there values when page is loaded. i also have 3 buttons for add new row , save , search. I want my grid view to show data from database when search button is clicked i.e select * from table where text box 1 and 2 equal to some thing. My HTML looks like.
AutoGenerateColumns="false" onselectedindexchanged="Gridview1_SelectedIndexChanged" BackColor="White"
BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
GridLines="Horizontal">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Item name">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" Height="25px" Width="119px"
DataTextField = "Item_name" Text='<%# Bind("Item_name") %>' DataValueField="Item_name"
AppendDataBoundItems="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub item">
<ItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" Height="25px" Width="119px"
AppendDataBoundItems="true"
DataValueField = "Sub_item" Text='<%# DataBinder.Eval(Container, "DataItem.Sub_item") %>' DataTextField = "Sub_item"
/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Location") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Permit number">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Permit no") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Applied">
<ItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server"
Height="25px" Width="119px"
DataTextField="Text" AppendDataBoundItems="true" Text='<%# DataBinder.Eval(Container, "DataItem.Applied") %>' DataValueField="Value" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Revision">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Revision") %>' ></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonSave" runat="server" Text="Save" OnClick="Save_Click" />
<asp:Button ID="ButtonAdd" runat="server" Text="Add Row" />
<asp:Button ID="search" runat="server" Text="Search" OnClick="Search_Click"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
on my search button click i have this code
if (TextBox4.Text != null && TextBox5.Text != null)
{
string job = TextBox4.Text.ToString();
string leg = TextBox5.Text.ToString();
string connString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (var conn = new SqlConnection(connString))
using (var cmd = conn.CreateCommand())
{
Response.Write(job);
Response.Write(leg);
conn.Open();
SqlCommand comand = new SqlCommand("SELECT * from Billing_heads where job# = '" + job + "' AND leg#='" + leg + "' ", conn);
// try
//{
SqlDataAdapter adp = new SqlDataAdapter(comand);
DataSet ds = new DataSet();
adp.Fill(ds);
//gvPros is the ID of GridView.
Gridview1.DataSource = ds;
Gridview1.DataBind();
Please help me that how can i bind my gridview because in Text='<%# Bind("Item_name") %>' property it saying the column name it says property with name "coloumn name " does not exists please help
Hi and thanks in advance,
I am trying to sort a gridview with linq and nothing is happening. I am not getting an error, but no sorting is happening in the view either. I am also using firebug for debugging as well.
asp:
<asp:GridView ID="GridViewRangeSetup" runat="server" AllowSorting="True" OnSorting="Gridview_Sort"
PagerStyle-Mode="NumericPages" AutoGenerateColumns="false" Width="100%" CssClass="gridView"
OnPageIndexChanging="GridViewRangeSetup_PageIndexChanging" AllowPaging="True"
PageSize="20" DataKeyNames="RangeId" OnRowCommand="GridViewRangeSetup_RowCommand"
OnRowEditing="GridViewRangeSetup_RowEditing" OnRowCancelingEdit="GridViewRangeSetup_CancelEditRow"
OnRowUpdating="GridViewRangeSetup_UpdateRow" OnRowDataBound="GridViewRangeSetup_RowDataBound">
<RowStyle CssClass="rowStyle"></RowStyle>
<HeaderStyle CssClass="headerBar" ForeColor="#ffffff"></HeaderStyle>
<AlternatingRowStyle CssClass="altRow" />
<Columns>
<asp:TemplateField HeaderText="Edit" HeaderStyle-Width="5%" HeaderStyle-ForeColor="#f2f2f2"
HeaderStyle-Font-Bold="false" HeaderStyle-Font-Size="Small">
<ItemTemplate>
<asp:ImageButton ID="imgEdit" runat="server" ImageUrl="~/images/icon_edit.png" CausesValidation="false"
CommandArgument='<%#Eval("RangeId") %>' CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="imgUpdate" runat="server" ImageUrl="~/images/icon_update.png"
CausesValidation="false" CommandArgument='<%#Eval("RangeId") %>' CommandName="Update" />
<asp:ImageButton ID="ImageCancel" runat="server" ImageUrl="~/images/icon_cancel.png"
CausesValidation="false" CommandArgument='<%#Eval("RangeId") %>' CommandName="Cancel" />
</EditItemTemplate>
<HeaderStyle Font-Bold="False" Font-Size="Small" ForeColor="#F2F2F2" Width="5%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete" HeaderStyle-Width="3%" HeaderStyle-ForeColor="#f2f2f2"
HeaderStyle-Font-Bold="false" HeaderStyle-Font-Size="Small">
<ItemTemplate>
<asp:ImageButton ID="imgDelete" runat="server" CausesValidation="false" OnClientClick="return DeleleAlert();"
CommandArgument='<%#Eval("RangeId") %>' CommandName="Remove" ImageUrl="~/images/icon_delete.png" />
</ItemTemplate>
<HeaderStyle Font-Bold="False" Font-Size="Small" ForeColor="#F2F2F2" Width="3%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" SortExpression="Description">
<EditItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" CssClass="textbox" Text='<%# Eval("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" SortExpression="Country.CountryName">
<EditItemTemplate>
<asp:DropDownList ID="ddlCountry" runat="server" CssClass="dropdown" AutoPostBack="True"
AppendDataBoundItems="true" DataTextField="CountryName" DataValueField="CountryId">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Bind("CountryName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="State/Province" SortExpression="GeographicRegion.RegionName">
<EditItemTemplate>
<asp:DropDownList ID="ddlRegion" runat="server" CssClass="dropdown" AutoPostBack="True"
AppendDataBoundItems="true" DataTextField="RegionName" DataValueField="GeographicRegionId">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblRegion" runat="server" Text='<%# Bind("RegionName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Base/Facility" SortExpression="Base.BaseName">
<EditItemTemplate>
<asp:DropDownList ID="ddlFacility" runat="server" CssClass="dropdown" AutoPostBack="True"
AppendDataBoundItems="true" DataTextField="BaseName" DataValueField="BaseId">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblFacility" runat="server" Text='<%# Bind("BaseName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Map Name" SortExpression="RangeMap.MapName">
<EditItemTemplate>
<asp:TextBox ID="txtMapName" runat="server" CssClass="textbox" Text='<%# Eval("MapName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblMapName" runat="server" Text='<%# Eval("MapName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Map">
<HeaderStyle HorizontalAlign="center" />
<ItemTemplate>
<asp:HyperLink ID="HyperLink_Map1" runat="server" NavigateUrl='<%# DataBinder.Eval(Container.DataItem,"MapPath") %>'
Text="">
<asp:Image ID="Image1" runat="server" ImageUrl='<%# DataBinder.Eval(Container.DataItem,"MapPath") %>'
Width="50px" Height="50px" />
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Low Latitude" SortExpression="RangeMap.LowLat">
<EditItemTemplate>
<asp:TextBox ID="txtLowLat" runat="server" CssClass="textbox" Text='<%# Eval("LowLat") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblLowLat" runat="server" Text='<%# Eval("LowLat") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Low Longitude" SortExpression="RangeMap.LowLong">
<EditItemTemplate>
<asp:TextBox ID="txtLowLong" runat="server" CssClass="textbox" Text='<%# Eval("LowLong") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblLowLong" runat="server" Text='<%# Eval("LowLong") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="High Latitude" SortExpression="RangeMap.HighLat">
<EditItemTemplate>
<asp:TextBox ID="txtHighLat" runat="server" CssClass="textbox" Text='<%# Eval("HighLat") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblHighLat" runat="server" Text='<%# Eval("HighLat") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="High Longitude" SortExpression="RangeMap.HighLong">
<EditItemTemplate>
<asp:TextBox ID="txtHighLong" runat="server" CssClass="textbox" Text='<%# Eval("HighLong") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblHighLong" runat="server" Text='<%# Eval("HighLong") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Button ID="RangeSetup_Status" CssClass="page-btn blue" CausesValidation="false"
CommandArgument='<%#Eval("RangeId") %> ' runat="server" Text="Status" OnClick="btnRangeStatus_Click">
</asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
c#
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
//Label2.Text = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
String column = e.SortExpression;
IQueryable<dynamic> sortedGridview = ConvertSortDirectionToSql(e.SortDirection) == "ASC" ?
(from r in context.Ranges.AsEnumerable()
where r.isDeleted == false
orderby typeof(WISSModel.Range).GetProperty(column).GetValue(r, null) ascending
select new
{
r.RangeId,
r.Description,
r.Country.CountryName,
r.GeographicRegion.RegionName,
r.Base.BaseName,
r.RangeMap.MapName,
r.RangeMap.MapPath,
r.RangeMap.LowLat,
r.RangeMap.LowLong,
r.RangeMap.HighLat,
r.RangeMap.HighLong
}).AsQueryable<dynamic>() :
(from r in context.Ranges.AsEnumerable()
where r.isDeleted == false
orderby typeof(WISSModel.Range).GetProperty(column).GetValue(r, null) descending
select new
{
r.RangeId,
r.Description,
r.Country.CountryName,
r.GeographicRegion.RegionName,
r.Base.BaseName,
r.RangeMap.MapName,
r.RangeMap.MapPath,
r.RangeMap.LowLat,
r.RangeMap.LowLong,
r.RangeMap.HighLat,
r.RangeMap.HighLong
}).AsQueryable<dynamic>();
//var sortedGridview = context.Ranges.Where("it.isDeleted == false").OrderBy(column);
GridViewRangeSetup.DataSource = sortedGridview.ToList();
//var test = sortedGridview.ToList();
//System.Diagnostics.Debugger.Break();
GridViewRangeSetup.DataBind();
}
Looks like it is not allowed to code order by parameters in string like in dynamic T-SQL. You should replace yout LINQ query with this one to make it work:
String column = e.SortExpression;
IQueryable<dynamic> sortedGridview = ConvertSortDirectionToSql(e.SortDirection) == "ASC" ?
(from r in context.Ranges
where r.isDeleted == false
orderby typeof(Range).GetProperty(column).GetValue(r,null) ascending
select new
{
r.RangeId,
Description = r.Description,
CountryName = r.Country.CountryName,
RegionName = r.GeographicRegion.RegionName,
BaseName = r.Base.BaseName,
r.RangeMap.MapName,
r.RangeMap.MapPath,
r.RangeMap.LowLat,
r.RangeMap.LowLong,
r.RangeMap.HighLat,
r.RangeMap.HighLong
}).AsQueryable<dynamic>() :
(from r in context.Ranges
where r.isDeleted == false
orderby typeof(Range).GetProperty(column).GetValue(r, null) descending
select new
{
r.RangeId,
Description = r.Description,
CountryName = r.Country.CountryName,
RegionName = r.GeographicRegion.RegionName,
BaseName = r.Base.BaseName,
r.RangeMap.MapName,
r.RangeMap.MapPath,
r.RangeMap.LowLat,
r.RangeMap.LowLong,
r.RangeMap.HighLat,
r.RangeMap.HighLong
}).AsQueryable<dynamic>();
Found another solution:
Using the DataSetLinqOperators class and modifying it slightly to allow null values:
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var sortedGridview = (from r in context.Ranges
where r.isDeleted == false
select new
{
r.RangeId,
r.Description,
r.Country.CountryName,
r.GeographicRegion.RegionName,
r.Base.BaseName,
r.RangeMap.MapName,
r.RangeMap.MapPath,
r.RangeMap.LowLat,
r.RangeMap.LowLong,
r.RangeMap.HighLat,
r.RangeMap.HighLong
}).ToList();
DataTable sortedTable = sortedGridview.CopyToDataTable();
sortedTable.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridViewRangeSetup.DataSource = sortedTable;
GridViewRangeSetup.DataBind();
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
int sort = (int)ViewState["Sort"];
switch (sort)
{
case 0:
newSortDirection = "ASC";
ViewState["Sort"] = 1;
break;
case 1:
newSortDirection = "DESC";
ViewState["Sort"] = 0;
break;
}
return newSortDirection;
}