grid view does not show data from database once bind - c#

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

Related

Gridview eval condition is not working properly

I am having database table with subject,faulty,hour.In the hour value am storing like 1,2,3,4 and 5 in the database.I want to disable the already clicked check box but in my result it is blocking the whole row not the particular check box.help me out from these problem.I have uploaded my sample code and database schema below
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="datee" HeaderText="Day/Hour" SortExpression="datee" />
<asp:TemplateField HeaderText="Hour1">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour1" runat="server" Checked='<%# Convert.ToBoolean((int)Eval("hour"))%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=1) %>' OnCheckedChanged="chkHour1_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour2">
<EditItemTemplate>
<asp:CheckBox ID="ChkColumn2" runat="server"/>
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour2" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour"))%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=2) %>' OnCheckedChanged="chkHour2_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour3">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn3" runat="server"/>
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour3" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour"))%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=3) %>' OnCheckedChanged="chkHour3_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour4">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn4" runat="server"/>
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour4" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour"))%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=4) %>' OnCheckedChanged="chkHour4_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour5">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn5" runat="server"/>
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour5" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour"))%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=5) %>' OnCheckedChanged="chkHour5_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
con.Open();
SqlDataAdapter cmd = new SqlDataAdapter("select DISTINCT datee,hour from tblfac order by datee", con);
DataTable dt = new DataTable("dt");
cmd.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
I clicked only 1 check box value but it is blocking the whole column.help me out from the problem
If I'm understanding the question correctly, the problem is that all five checkboxes in the row are checked, regardless of what the value of hour is. This is because you are using
Checked='<%#Convert.ToBoolean((int)Eval("hour"))%>'
to set the value of the checkbox. You are converting the integer value of hour to a boolean value. Convert.ToBoolean will translate any non-zero integer to true, so as long as hour isn't zero, the checkbox will be checked.
Working example:
Creating datasource in code-behind:
DataTable dt = new DataTable("dt");
dt.Columns.Add("datee", typeof(string));
dt.Columns.Add("hour", typeof(int));
dt.Rows.Add("06-Jul-15 12:00:00 AM",1);
dt.Rows.Add("07-Jul-15 12:00:00 AM",2);
dt.Rows.Add("08-Jul-15 12:00:00 AM",3);
dt.Rows.Add("09-Jul-15 12:00:00 AM",4);
dt.Rows.Add("10-Jul-15 12:00:00 AM",5);
GridView1.DataSource = dt;
GridView1.DataBind();
Gridview:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="datee" HeaderText="Day/Hour" SortExpression="datee" />
<asp:TemplateField HeaderText="Hour1">
<ItemTemplate>
<asp:CheckBox ID="chkHour1" runat="server" Checked='<%# Convert.ToBoolean((int)Eval("hour")==1)%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=1) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour2">
<ItemTemplate>
<asp:CheckBox ID="chkHour2" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour")==2)%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=2) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour3">
<ItemTemplate>
<asp:CheckBox ID="chkHour3" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour")==3)%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=3) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour4">
<ItemTemplate>
<asp:CheckBox ID="chkHour4" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour")==4)%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=4) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour5">
<ItemTemplate>
<asp:CheckBox ID="chkHour5" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour")==5)%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=5) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Results showing only one box checked, and that box disabled:

Select Command and Search command are not working properly in gridview

all my commands are working properly but the problem is
after I execute my Search command then I click the select link button on my GridView, My Gridview is refreshing and select the first row in the grid view and not the one that I searched.. example: first I run the Index Page then the GridView get all the record from database(10 populated record) and show to the index.. (No Problem)
then I type the firstname of the user to search it then i click the search button then the it filtered and show to gridview again here's the image
then I click the "Select" link button from Gridview and this what happened
that's what happened .. I clicked the select link button on "marcy's record" then it refreshed and get the value of RASI's Record on the first row...
but when my click select without searching it worked just fine
here's my code for search button
string strconn;
strconn = "select * from User_TBL_DB where (Firstname like '%'+#search+'%' and Middlename like '%'+#search2+'%' and Lastname like '%'+#search3+'%')";
SqlCommand xp = new SqlCommand(strconn, conn);
xp.Parameters.Add("#search", SqlDbType.NVarChar).Value = firstname_search.Text;
xp.Parameters.Add("#search2", SqlDbType.NVarChar).Value = middlename_search.Text;
xp.Parameters.Add("#search3", SqlDbType.NVarChar).Value = lastname_search.Text;
conn.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
GridView1.DataSource = ds;
GridView1.DataBind();
conn.Close();
and here's my code for select link button on gridview
row = GridView1.SelectedRow;
firstname_tb.Text = (row.FindControl("lbl_Firstname") as Label).Text;
middlename_tb.Text = (row.FindControl("lbl_Middlename") as Label).Text;
lastname_tb.Text = (row.FindControl("lbl_Lastname") as Label).Text;
age_tb.Text = (row.FindControl("lbl_Age") as Label).Text;
id_tb.Text = (row.FindControl("lbl_ID") as Label).Text;
string gender = (row.FindControl("lbl_Sex") as Label).Text;
if (gender == "FEMALE")
{
female_rb.Checked = true;
male_rb.Checked = false;
}
else
{
male_rb.Checked = true;
female_rb.Checked = false;
}
and here's my codes for ASP on Gridview
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="4" AutoGenerateColumns="False"
onselectedindexchanged="GridView1_SelectedIndexChanged" Width="581px"
onrowcommand="GridView1_RowCommand"
onselectedindexchanging="GridView1_SelectedIndexChanging">
<Columns>
<%--<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="Select_button" CommandArgument ='<%# Eval("ID") %>' CommandName="SelectRow" ForeColor="#8C4510" runat="server">Select</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:CommandField ShowSelectButton="True"></asp:CommandField>
<asp:TemplateField HeaderText="Firstname" SortExpression="Firstname">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Firstname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Firstname" runat="server" Text='<%# Bind("Firstname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Middlename" SortExpression="Middlename">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Middlename") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Middlename" runat="server" Text='<%# Bind("Middlename") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lastname" SortExpression="Lastname">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Lastname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Lastname" runat="server" Text='<%# Bind("Lastname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age" SortExpression="Age">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Age") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Age" runat="server" Text='<%# Bind("Age") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sex" SortExpression="Sex">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("Sex") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Sex" runat="server" Text='<%# Bind("Sex") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<EditItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True"
ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399"
HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True"
ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
i connect it to sqlDatasource1 and disconnect it and leave the code as is. I used Showselectbutton="true"
that's my Problem hope you can help me thank you very much

DataBinding a Radiobutton group

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();
};

Understanding Gridview RowCommand

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];

Using identifier in gridview

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.

Categories

Resources