Cannot update selected lines from data in gridview - asp.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services.Description;
namespace Lab06
{
public partial class AssignmentAttendance : System.Web.UI.Page
{
Student sStudent = new Student();
Attendance aAttendance = new Attendance();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}
protected void bind()
{
List<Student> acclist = new List<Student>();
acclist = sStudent.getAccountAll();
GridView1.DataSource = acclist;
GridView1.DataBind();
}
protected void Retrieve_Attendance_Click(object sender, EventArgs e)
{
string _connStr = ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString;
SqlConnection SQLConn = new SqlConnection(_connStr);
/* string username = Session["User"].ToString();*/
SqlCommand cmd = new SqlCommand("SELECT * FROM Student WHERE ClassCode = #ClassCode", SQLConn);
SQLConn.Open();
cmd.Parameters.AddWithValue("#ClassCode", tb_classcode.Text);
cmd.ExecuteNonQuery();
SQLConn.Close();
SqlDataAdapter SQLAdapter = new SqlDataAdapter(cmd);
DataTable DT = new DataTable();
SQLAdapter.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int result = 0;
Student stud = new Student();
string categoryID = GridView1.DataKeys[e.RowIndex].Value.ToString();
result = stud.AccountDelete(categoryID);
if (result > 0)
{
Response.Write("<script>alert('Student Remove successfully');</script>");
}
else
{
Response.Write("<script>alert('Student Removal NOT successfully');</script>");
}
Response.Redirect("AssignmentAttendance.aspx");
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int result = 0;
Student stud = new Student();
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
string tStudent_ID = ((TextBox)row.Cells[0].Controls[0]).Text;
string tClassCode = ((TextBox)row.Cells[3].Controls[0]).Text;
result = stud.AttendanceUpdate(tClassCode, tStudent_ID);
/*if (result > 0)
{
Response.Write("<script>alert('Product updated successfully');</script>");
}
else
{
Response.Write("<script>alert('Product NOT updated');</script>");
}*/
GridView1.EditIndex = -1;
bind();
}
}
}
Above is my AssignmentAttendance.aspx.cs code
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="AssignmentAttendance.aspx.cs" Inherits="Lab06.AssignmentAttendance" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<p>
Attendance</p>
<p>
Filter Search</p>
<p>
Class code <asp:TextBox ID="tb_classcode" runat="server"></asp:TextBox>
</p>
<p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="168px" Width="1451px" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:BoundField AccessibleHeaderText="Joe" DataField="Student_ID" HeaderText="Student_ID" />
<asp:BoundField AccessibleHeaderText="Joe" DataField="Name" HeaderText="Name" />
<asp:BoundField AccessibleHeaderText="Joe" DataField="Pass" HeaderText="Pass" />
<asp:BoundField DataField="ClassCode" HeaderText="ClassCode" />
<asp:CommandField AccessibleHeaderText="Joe" ShowDeleteButton="True" ShowEditButton="True" />
</Columns>
</asp:GridView>
</p>
<asp:Button ID="Retrieve_Attendance" runat="server" Text="Confirm" style="float:right;" OnClick="Retrieve_Attendance_Click" />
</asp:Content>
Above is my AssignmentAttendance.aspx codes
My normal retrieve works however, when I click on the update button, it will not update the current data it has in the gridview but in fact retrieve all the data from the db and display it into the grid view.
My normal retrieve
My gridview after pressing update
Anyone know why this happens?

Related

Save Cancel button event handler is not working in Radscheduler advance insert form

In my application I have a radschedular , when creating a new appointment I am opening in advance mode by specifying StartInsertingInAdvancedForm="True"
My code is given below
.aspx
<telerik:RadScheduler RenderMode="Lightweight" runat="server" ID="rs_course_schedule" CustomAttributeNames="Completed"
StartInsertingInAdvancedForm="True" StartEditingInAdvancedForm="True"
FirstDayOfWeek="Monday" LastDayOfWeek="Friday" Reminders-Enabled="true" SelectedView="WeekView"
RowHeight="30px" AppointmentStyleMode="Simple" OnAppointmentDataBound="RadScheduler1_AppointmentDataBound"
OnAppointmentCommand="rs_course_schedule_OnAppointmentCommand"
OnAppointmentCreated="RadScheduler1_AppointmentCreated" OverflowBehavior="Auto" Skin="Web20"
OnAppointmentInsert="rs_course_schedule_OnAppointmentInsert">
<AdvancedForm Modal="true"></AdvancedForm>
<AppointmentTemplate>
<div class="appointmentHeader">
<asp:Panel ID="RecurrencePanel" CssClass="rsAptRecurrence" runat="server" Visible="false">
</asp:Panel>
<asp:Panel ID="RecurrenceExceptionPanel" CssClass="rsAptRecurrenceException" runat="server"
Visible="false">
</asp:Panel>
<asp:Panel ID="ReminderPanel" CssClass="rsAptReminder" runat="server" Visible="false">
</asp:Panel>
<%#Eval("Subject") %>
</div>
<div>
Assigned to: <strong>
<asp:Label ID="UserLabel" runat="server" Text='<%# Container.Appointment.Resources.GetResourceByType("Faculty") == null ? "None" : Container.Appointment.Resources.GetResourceByType("Faculty").Text %>'></asp:Label>
</strong>
<br />
<asp:CheckBox ID="CompletedStatusCheckBox" runat="server" Text="Completed? " TextAlign="Left"
Checked='<%# !String.IsNullOrEmpty(Container.Appointment.Attributes["Completed"]) && Boolean.Parse(Container.Appointment.Attributes["Completed"]) %>'
AutoPostBack="true" OnCheckedChanged="CompletedStatusCheckBox_CheckedChanged"></asp:CheckBox>
</div>
</AppointmentTemplate>
<ResourceStyles>
<telerik:ResourceStyleMapping Type="Faculty" Key="1" BackColor="red"></telerik:ResourceStyleMapping>
<telerik:ResourceStyleMapping Type="Faculty" Key="2" BackColor="Pink"></telerik:ResourceStyleMapping>
<telerik:ResourceStyleMapping Type="Faculty" Key="3" BackColor="OrangeRed"></telerik:ResourceStyleMapping>
</ResourceStyles>
</telerik:RadScheduler>
in code behind
public partial class Schedule : System.Web.UI.UserControl
{
#region Object Instantiation
readonly BEL_LMS _objLms = new BEL_LMS();
readonly BL_LMS _blLms = new BL_LMS();
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateSchedular();
AddTeachers();
SetDate();
}
}
private void AddTeachers()
{
_objLms.ActivityId = Session["activity_id"].ToString();
DataTable dtFaculty = _blLms.AssignedFaculty(_objLms);
ResourceType resources = new ResourceType("Faculty");
if (dtFaculty.Rows.Count > 0)
{
resources.DataSource = dtFaculty;
resources.KeyField = "userid";
resources.TextField = "acct_name";
resources.ForeignKeyField = "UserId";
rs_course_schedule.ResourceTypes.Add(resources);
}
}
private void SetDate()
{
rs_course_schedule.SelectedDate = DateTime.Now;
}
private void PopulateSchedular()
{
_objLms.Flag = "fetch";
_objLms.ActivityId = "11";
DataTable dtTable = _blLms.FetchScheduleForCourse(_objLms);
if (dtTable.Rows.Count > 0)
{
rs_course_schedule.DataKeyField = "ID";
rs_course_schedule.DataStartField = "Start";
rs_course_schedule.DataEndField = "End";
rs_course_schedule.DataSubjectField = "Subject";
rs_course_schedule.DataDescriptionField = "Description";
//rs_course_schedule.DataReminderField = "Reminder";
rs_course_schedule.DataSource = dtTable;
rs_course_schedule.DataBind();
}
}
protected void CompletedStatusCheckBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox CompletedStatusCheckBox = (CheckBox)sender;
//Find the appointment object to directly interact with it
SchedulerAppointmentContainer appContainer = (SchedulerAppointmentContainer)CompletedStatusCheckBox.Parent;
Appointment appointment = appContainer.Appointment;
_objLms.ActivityId = appointment.ID.ToString();
_objLms.Flag = "update";
int affectedRow = _blLms.UpdateCourse(_objLms); // update checkbox data for that particular schedule
rs_course_schedule.Rebind();
}
protected void RadScheduler1_AppointmentDataBound(object sender, SchedulerEventArgs e)
{
if (e.Appointment.Attributes["Completed"] == "True")
{
e.Appointment.BackColor = System.Drawing.Color.Red;
}
}
protected void RadScheduler1_AppointmentCreated(object sender, AppointmentCreatedEventArgs e)
{
}
protected void rs_course_schedule_OnAppointmentInsert(object sender, AppointmentInsertEventArgs e)
{
SchedulerDataSource.InsertParameters["End"].DefaultValue = e.Appointment.End.ToString();
SchedulerDataSource.InsertParameters["Start"].DefaultValue = e.Appointment.Start.ToString();
SchedulerDataSource.InsertParameters["Subject"].DefaultValue = e.Appointment.Start.ToString();
SchedulerDataSource.InsertParameters["Description"].DefaultValue = e.Appointment.Description;
SchedulerDataSource.InsertParameters["CourseID"].DefaultValue = "1";
//SchedulerDataSource.InsertParameters["User"].DefaultVal;
}
protected void rs_course_schedule_OnAppointmentCommand(object sender, AppointmentCommandEventArgs e)
{
string name = e.CommandName;
}
}
}
Now when I am trying to insert a new appointment this form is opening
But in Save and Cancel button click is not occurring..
How I can solve this issue ?

Loosing Attributes in DropDownList asp.net

I set attributes into a dropdownlist
the problem is that when I try to read them in a button click I get null !!
I am not sure of this is something to do with the postback or not but you will see my code below
Why is that and how to fix it?
This is my Code
protected void ddlReps_DataBound(object sender, EventArgs e)
{
foreach (System.Data.DataRow row in dt.Rows)
{
ddlReps.Items.FindByValue(row["ReportID"].ToString()).Attributes.Add("ReportPath", row["ReportPath"].ToString());
ddlReps.Items.FindByValue(row["ReportID"].ToString()).Attributes.Add("ReportServer", row["ReportServer"].ToString());
}
string AttribValue1 = ddlReps.SelectedItem.Attributes["ReportPath"];
//When I check here I can see the valu
}
protected void btnViewReport_Click(object sender, EventArgs e)
{
string AttribValue2 = ddlReps.SelectedItem.Attributes["ReportPath"];
//Here is null :(
}
ALso here is the page load code
protected void Page_Load(object sender, EventArgs e)
{
if (!User.Identity.IsAuthenticated) // if the user is already logged in
{
Response.Redirect("~/AccessDenied.aspx");
}
if (!Page.IsPostBack)
{
if (Session["USERNAME"] != null)
{
lblWelcome.Text = "Welcome back " + Session["USERNAME"].ToString();
}
string connStr = ConfigurationManager.ConnectionStrings["Main"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("mySP", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
if (dt.Rows.Count > 0)
{
//Populate your DropDownList
ddlReps.DataSource = dt;
ddlReps.DataTextField = "ReportName";
ddlReps.DataValueField = "ReportID";
ddlReps.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
and here is the markeup for the ddl
the asp:ScriptManager is used because i am using ReportViewer
<div>
<form id="form2" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div class="report-module">
<h2>Choose your report</h2>
<asp:DropDownList ID="ddlReps" runat="server" OnDataBound="ddlReps_DataBound" CssClass="ddl" ViewStateMode="Enabled"></asp:DropDownList>
</div>
<rsweb:ReportViewer ID="reportViewer" runat="server" Width="100%" ProcessingMode="Remote" Font-Names="sans-serif" Font-Size="8pt" WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt" Height="457px" BackColor="White" Visible="False" SplitterBackColor="51, 181, 229">
</rsweb:ReportViewer>
</form>
</div>

when redirecting to a page that was initially in edit mode to a readonly mode the gridview doesnot appear but text box appears in asp.net

I have 2 pages (Trial.aspx and TestCallBack.aspx). Trail.aspx will first be editable mode. Now from TestCallBack.aspx i will redirect back to Trail.aspx but all the controls should be read only format. I have given the source code details below. Only the textbox of trial.aspx is readonly, the gridview is not seen at all.
Trial.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Trial.aspx.cs" Inherits="PTest.Trial" EnableEventValidation ="true" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtVisitor" runat="server"></asp:TextBox>
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" ShowHeaderWhenEmpty ="true" Visible ="true">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Trial.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace PTest
{
public partial class Trial : System.Web.UI.Page
{
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("txtDate");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("txtDate");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string name = Request.QueryString["value"];
if (name == "true")
{
hidecontrols();
}
else
{
SetInitialRow();
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void hidecontrols()
{
foreach (Control c in Page.Controls)
{
if (c is GridView)
((GridView)(c)).Enabled = false;
foreach (Control ctrl in c.Controls)
{
if (ctrl is TextBox)
{
((TextBox)(ctrl)).Enabled = false;
}
else if (ctrl in GridView)
{
((GridView)(ctrl).Enabled =false;
}
}
}
}
}
}
TestCallBack.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestCallBack.aspx.cs" Inherits="PTest.TestCallBack" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
TestCallBack.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PTest
{
public partial class TestCallBack : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Trial.aspx?value=true");
}
}
}
After reading your comment it would appear your problem is here:
if (!Page.IsPostBack)
{
string name = Request.QueryString["value"];
if (name == "true")
{
hidecontrols();
}
else
{
SetInitialRow();
}
}
You're essentially saying If this page isn't a postback then perform this IF statement - and then in the IF statement you're saying IF there is a qstring value hide controls. Since you are redirecting back to this page it will not be a postback, and since you will have a qstring value it will hide the controls.
Perhaps try something like this:
SetInitialRow();
if (!Page.IsPostBack)
{
string name = Request.QueryString["value"];
if (name == "true")
{
GridView1.ShowFooter = false;
}
else
{
GridView1.ShowFooter = true;
}
}
Not sure if this is what you're actually after, though the problem is with your if-else in your page load. Perhaps if you update your Q with the actual flow you're after; it would help us help you more.

Store procedure select from two different table to a grid view

I'm looking for some help in a matter i can't solve it.
i created a stored procedure to select data from a table called "applicant"
and it work great
this is the code below:
USE [Josons]
GO
/****** Object: StoredProcedure [dbo].[PROC_GETALLAPPLICANTS] Script Date: 09/03/2013 10:50:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Batch submitted through debugger: SQLQuery25.sql|7|0|C:\Users\supportadmin\AppData\Local\Temp\~vs29E1.sql
ALTER PROCEDURE [dbo].[PROC_GETALLAPPLICANTS]
AS
BEGIN
select ID,FIRSTNAME,LASTNAME,APPLYDATE from APPLICANT order by ID Asc
END
i added a new table called "AF", the two tables are related with a unique column:"applicant_id"
how to make the store procedure to select from 2 tables and show it in one grid view with the same order "ID Asc"
Edit:
aspx file:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPages/MainMasterPage.master"
AutoEventWireup="true" CodeFile="HR.aspx.cs" Inherits="Pages_HR" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div>
<asp:Button ID="btnLogout" CssClass="btnLogoutStyle" runat="server"
Text="Logout" onclick="btnLogout_Click" />
</div>
<div class="divgvDisplayAllApplicantsStyle">
<asp:GridView
ID="gvDisplayAllApplicants"
CssClass="gridviewstyle"
runat="server"
OnRowDataBound="gvDisplayAllApplicants_RowDataBound"
AllowPaging="true"
PageSize="10"
OnPageIndexChanging="gvDisplayAllApplicants_PageIndexChanging"
OnSelectedIndexChanged="gvDisplayAllApplicants_SelectedIndexChanged"
DataKeyNames="ID"
Width="940"
AutoGenerateColumns="false">
<Columns>
<asp:ButtonField CommandName="Select" Visible="false" />
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" />
<asp:TemplateField HeaderText="AF #">
<ItemTemplate>
<%# Eval("AF")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<%# Eval("FIRSTNAME")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<%# Eval("LASTNAME")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Apply Date">
<ItemTemplate>
<%# Eval("APPLYDATE")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</asp:Content>
and the aspx.cs file :
public partial class Pages_HR : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["DisplaySelectedApplicant"] = "DisplaySelectedApplicant";
try
{
if (Session["HR"].ToString() == "" && Request.QueryString["queryStringBackButton"].ToString() == null)
{
Session["DisplaySelectedApplicant"] = "";
Session["HR"] = "";
Response.Redirect("LoginPage.aspx");
}
}
catch (NullReferenceException)
{
Response.Redirect("LoginPage.aspx");
}
}
FillApplicantGridView();
}
#region METHODS
public void FillApplicantGridView()
{
string connstr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
using (SqlConnection sqlconnection = new SqlConnection(connstr))
{
sqlconnection.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "PROC_GETALLAPPLICANTS";
cmd.Connection = sqlconnection;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
DataTable datatable = new DataTable();
sqlDataAdapter.Fill(datatable);
gvDisplayAllApplicants.DataSource = datatable;
gvDisplayAllApplicants.DataBind();
sqlconnection.Close();
}
}
}
protected void gvDisplayAllApplicants_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get reference to button field in the gridview.
LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "Select$" + e.Row.RowIndex);
e.Row.Style["cursor"] = "hand";
e.Row.Attributes["onclick"] = _jsSingle;
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#93A3B0'; this.style.color='White'; this.style.cursor='pointer'");
e.Row.Attributes.Add("onmouseout", String.Format("this.style.color='Black';this.style.backgroundColor='White';", gvDisplayAllApplicants.RowStyle.BackColor.ToKnownColor()));
}
}
}
protected void gvDisplayAllApplicants_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow selectedRow = gvDisplayAllApplicants.SelectedRow;
int rowIndex = selectedRow.RowIndex;
string Applicant_ID = gvDisplayAllApplicants.DataKeys[rowIndex].Values["ID"].ToString();
Response.Redirect("DisplaySelectedApplicant.aspx?ID=" + Applicant_ID);
}
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow row in gvDisplayAllApplicants.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
ClientScript.RegisterForEventValidation(((LinkButton)row.Cells[0].Controls[0]).UniqueID, "Select$" + row.RowIndex);
}
}
base.Render(writer);
}
protected void gvDisplayAllApplicants_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvDisplayAllApplicants.PageIndex = e.NewPageIndex;
gvDisplayAllApplicants.ShowFooter = false;
gvDisplayAllApplicants.EditIndex = -1;
FillApplicantGridView();
}
#endregion
protected void btnLogout_Click(object sender, EventArgs e)
{
Response.Redirect("LoginPage.aspx");
}
}
Thanks,
If you want all records where both tables have application_id, then use INNER JOIN...
SELECT ap.ID ,
ap.FIRSTNAME ,
ap.LASTNAME ,
ap.APPLYDATE ,
AF.FieldNames
FROM APPLICANT ap
INNER JOIN AF ON ap.applicant_id = AF.applicant_id
ORDER BY ap.ID ASC
If you want to return all Applicants, even if there is no corresponding relation in AF, then use LEFT JOIN...
SELECT ap.ID ,
ap.FIRSTNAME ,
ap.LASTNAME ,
ap.APPLYDATE ,
AF.FieldNames
FROM APPLICANT ap
LEFT JOIN AF ON ap.applicant_id = AF.applicant_id
ORDER BY ap.ID ASC
Example of using ISNULL if no records...
SELECT ap.ID ,
ap.FIRSTNAME ,
ap.LASTNAME ,
ap.APPLYDATE ,
ISNULL(AF.AppFormCourseName, 'No Application as of yet')
FROM APPLICANT ap
LEFT JOIN AF ON ap.applicant_id = AF.applicant_id
ORDER BY ap.ID ASC
Consider calling the AF table something better too, I'm guessing it could be ApplicationForm?
See the explanation here for both Inner Join and Left Join.
ALTER PROCEDURE [dbo].[PROC_GETALLAPPLICANTS] AS
BEGIN
select a.ID,a.FIRSTNAME,a.LASTNAME,a.APPLYDATE,af.* from APPLICANT a join AF af on a.applicant_id = af.applicant_id order by a.ID Asc
END

gridview not showing new updated values when rowupdating event is triggered

am using a gridview. When I click on the edit button the update and cancel button appear. Upon modifying the values in textbox which come from EditItemTemplate , the new values dont show in the event handler rowupdating(), instead I get the values which appear when the page was rendered. How do I grab the new values from these textboxes and proceed further? Here is the code.
aspx page
<%# Page Language="C#" MasterPageFile="~/Master Pages/FacultyMasterpage.master" AutoEventWireup="true" CodeFile="FacultyQuestion.aspx.cs" Inherits="Faculty_FacultyQuestion" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Content10" Runat="Server">
<br />
<br />
<asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4"
AllowPaging="True" AutoGenerateEditButton="True"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating">
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<RowStyle BackColor="White" ForeColor="#330099" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>
<br />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Content20" Runat="Server">
</asp:Content>
cs file coading
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Faculty_FacultyQuestion : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
private void BindData()
{
DataTable dt = Class3.QuestionForFaculty(Convert.ToInt32(Session["rid"]));
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
GridView1.EditIndex = -1;
BindData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
{
//Retrieve the table from the session object.
DataTable dt = Class3.QuestionForFaculty(Convert.ToInt32(Session["rid"]));
GridView1.DataSource = dt;
GridView1.DataBind();
//Update the values.
GridViewRow row = GridView1.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["ans"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
GridView1.EditIndex = -1;
BindData();
}
}
}
class 3 coading
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.ComponentModel;
[DataObject]
/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{
private static string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
[DataObjectMethod(DataObjectMethodType.Select)]
public static DataTable getall()
{
SqlDataAdapter dp = new SqlDataAdapter("Select * from Question", conn);
DataSet ds = new DataSet();
dp.Fill(ds, "Question");
return ds.Tables["Question"];
}
[DataObjectMethod(DataObjectMethodType.Delete)]
public static int delete(int qid)
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("Delete into Question qid = #a", con);
cmd.Parameters.Add("#a", SqlDbType.VarChar).Value = qid;
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
return(i);
}
[DataObjectMethod(DataObjectMethodType.Select)]
public static DataTable QuestionForFaculty(int rid)
{
SqlDataAdapter dp = new SqlDataAdapter("SELECT Question.question, Question.ans,Question.qid, Subject.subjectname, Question.posteddate, Registration.name, Registration.role, Registration.rid FROM Question INNER JOIN Registration ON Question.rid = Registration.rid INNER JOIN Subject ON Question.sid = Subject.subjectid WHERE (Question.fid = '"+rid+"')", conn);
DataSet ds = new DataSet();
dp.Fill(ds, "Question");
return ds.Tables["Question"];
}
}
Why are you databinding the GridView at the start of the OnRowUpdating event? That right there is your problem! Just remove this:
GridView1.DataSource = dt;
GridView1.DataBind();
UPDATE: first add this to your Class3 (purely based on your sample code - not tested):
[DataObjectMethod(DataObjectMethodType.Update)]
public static int UpdateAnswer(int qid, string ans)
{
var con = new SqlConnection(conn);
var cmd = new SqlCommand("UPDATE Question SET ans = #ans WHERE qid = #qid", con);
cmd.Parameters.Add("#qid", SqlDbType.VarChar).Value = qid;
cmd.Parameters.Add("#ans", SqlDbType.VarChar).Value = ans;
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
return(i);
}
Then change OnRowUpdating event to:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Class3.UpdateAnswer(row.DataItemIndex, ((TextBox)row.Cells[2].Controls[0]).Text);
GridView1.EditIndex = -1;
BindData();
}

Resources