Listbox in UpdatePanel doesn't trigger the second time - c#

The list box in the below updatePanel triggers the postback only once, for example if I select pre-Purchase on ddlroot it loads the appropriate data on ddlchild, but if I select post-order again it doesn't load the data needed.
<asp:UpdatePanel ID="UpdatePanel5" ChildrenAsTriggers="true" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlroot" EventName="TextChanged" />
<asp:AsyncPostBackTrigger ControlID="ddlchild" EventName="Textchanged" />
</Triggers>
<ContentTemplate>
<table>
<tr>
<td>
<asp:ListBox ID="ddlroot" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlroot_SelectedIndexChanged">
<asp:ListItem Value="pre-purchase" Text="Pre-Purchase"></asp:ListItem>
<asp:ListItem Value="post-purchase" Text="Post-Purchase"></asp:ListItem>
</asp:ListBox>
</td>
<td>
<asp:ListBox ID="ddlchild" runat="server"></asp:ListBox>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Below would be the server side code where based on the ddlroot selection the data will be fetched from MySql database,
protected void ddlroot_SelectedIndexChanged(object sender, EventArgs e)
{
ddlchild.Items.Clear();
string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
if (ddlroot.SelectedValue == "pre-purchase")
{
using (MySqlConnection conn = new MySqlConnection(MyConString))
{
using (MySqlCommand cmd1 = new MySqlCommand())
{
cmd1.CommandText = "select distinct(prePurchase) from prepurchase WHERE prePurchase IS NOT NULL";
cmd1.Connection = conn;
conn.Open();
using (MySqlDataReader sdr1 = cmd1.ExecuteReader())
{
while (sdr1.Read())
{
ListItem item1 = new ListItem();
item1.Text = sdr1["prePurchase"].ToString();
item1.Value = sdr1["prePurchase"].ToString();
ddlchild.Items.Add(item1);
}
}
conn.Close();
}
}
}
else if(ddlroot.SelectedValue == "post-purchase")
{
using (MySqlConnection conn = new MySqlConnection(MyConString))
{
using (MySqlCommand cmd1 = new MySqlCommand())
{
cmd1.CommandText = "select distinct(postPurchase) from prepurchase WHERE postPurchase IS NOT NULL";
cmd1.Connection = conn;
conn.Open();
using (MySqlDataReader sdr1 = cmd1.ExecuteReader())
{
while (sdr1.Read())
{
ListItem item1 = new ListItem();
item1.Text = sdr1["postPurchase"].ToString();
item1.Value = sdr1["postPurchase"].ToString();
ddlchild.Items.Add(item1);
}
}
conn.Close();
}
}
}
//UpdatePanel5.Update();
}
How can I fix this?

Related

inserting text into SQL from a drop down list in C#

Help is very much needed and appreciated. I am working on a project that requires me to select a value from a drop down menu, and insert it into my database. The drop down list is loaded through a stored proc and data binding, and works well. But when I press the button to insert the data, it will ONLY insert the default text -- Select Chemical -- , or if that is not there, it will insert whatever is in the first selection. It never sees the other items.
My CONTENT Code:
<table width="95%" style="padding-left:200px; padding-top:50px">
<tr>
<td style="font-size:large; font-weight:bold; padding-bottom:50px">
<asp:DropDownList ID="ChemLot" runat="server">
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2" align="center" >
<asp:Label ID="lblchemMessage" runat="server" Visible="false" />
</td>
</tr>
<tr>
<td colspan="2" align="center" >
<br />
<br />
<asp:Button ID="AddChemLots" OnClick= "AddChemLot2" Text="Add New Chemical Lot" Font-Bold="true" runat="server" Height="50px" Width="250px" BackColor="Azure" />
</td>
</tr>
</table>
The Code BEHIND:
protected void AddChemLot2(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
String chemical = ChemLot.SelectedItem.Text.ToString();
SqlConnection m_sqlConnection;
string m_connectionString = ConfigurationManager.ConnectionStrings["ChemicalConnectionString"].ConnectionString;
using (m_sqlConnection = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand("Insert_Chem"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = m_sqlConnection;
m_sqlConnection.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ChemName", chemical);
}
int check = cmd.ExecuteNonQuery();
m_sqlConnection.Close();
My Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
LoadList();
}
}
public void LoadList()
{
string constr = ConfigurationManager.ConnectionStrings["ChemicalConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Load_Chem"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
ChemLot.DataSource = cmd.ExecuteReader();
ChemLot.DataTextField = "Chemical";
ChemLot.DataBind();
con.Close();
}
}
You should use SelectedItem.Value or SelectedValue instead like
String chemical = ChemLot.SelectedItem.Value.ToString();
Additional: There is no point in checking the below condition inside event handler since it will always be true
if (Page.IsPostBack)
{
As I see from your current edit: you have below. You haven't specified the DataValueField at all anywhere.
ChemLot.DataTextField = "Chemical";
ChemLot.DataBind();
You should specify both
ChemLot.DataTextField = "Chemical";
ChemLot.DataValueField = <something>;
ChemLot.DataBind();

why is no data present in my asp c# code?

I have a table of assignments. I want to get the total number of points earned by an enrolled student and the total number of points possible for that student. I have an asp class that calculates the letter grade and updates the enrollment record in the database with the letter grade. I keep getting the error Invalid attempt to read when no data is present. I have pointed out the line the error occurs on.
This is my assignments table:
As you can see, there are plenty of assignments for enrollmentId 69. I use the following stored procedure to get the assignments:
ALTER PROCEDURE [dbo].[GetScores]
#enrollmentId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT sum(pointsEarned) AS totalEarned, sum(pointsPossible) AS totalPossible, enrollmentId
FROM Assignments
WHERE enrollmentId = #enrollmentId
GROUP BY pointsEarned, pointsPossible, enrollmentId
END
This is the code-behind file:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
PopulateSemesterList();
}
private void PopulateSemesterList()
{
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.GetSemesters", conn);
conn.Open();
DDSemesters.DataSource = cmd.ExecuteReader();
DDSemesters.DataTextField = "semesterName";
DDSemesters.DataValueField = "semesterId";
this.DataBind();
conn.Close();
conn.Dispose();
DDSemesters.Items.Insert(0, new ListItem("Select Semester", "0"));
DDSemesters.SelectedIndex = 0;
}
protected void DDSemesters_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList DDSemesters = sender as DropDownList;
int selectedSemester = Convert.ToInt32(DDSemesters.SelectedItem.Value);
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.GetCourses", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#semesterId", selectedSemester));
conn.Open();
DDCourses.DataSource = cmd.ExecuteReader();
DDCourses.DataTextField = "courseName";
DDCourses.DataValueField = "courseId";
this.DataBind();
conn.Close();
conn.Dispose();
DDCourses.Items.Insert(0, new ListItem("Select Course", "0"));
DDCourses.SelectedIndex = 0;
DDCourses.Visible = true;
CoursesLbl.Visible = true;
}
protected void DDCourses_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList DDCourses = sender as DropDownList;
int selectedCourse = Convert.ToInt32(DDCourses.SelectedItem.Value);
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.CourseEnrollment", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#courseId", selectedCourse));
conn.Open();
DDStudents.DataSource = cmd.ExecuteReader();
DDStudents.DataTextField = "fullName";
DDStudents.DataValueField = "enrollmentId";
this.DataBind();
conn.Close();
conn.Dispose();
DDStudents.Items.Insert(0, new ListItem("Select Student", "0"));
DDStudents.SelectedIndex = 0;
DDStudents.Visible = true;
StudentLbl.Visible = true;
}
protected void DDStudents_SelectedIndexChanged(object sender, EventArgs e)
{
assignmentInfoDiv.Visible = true;
studentName.Text = DDStudents.SelectedItem.Text;
}
protected void SaveScore_Click(object sender, EventArgs e)
{
Grades studentGrade = new Grades();
studentGrade.courseId = Convert.ToInt32(DDCourses.SelectedItem.Value);
studentGrade.enrollmentId = Convert.ToInt32(DDStudents.SelectedItem.Value);
studentGrade.assignmentName = AssignmentList.SelectedItem.Text;
studentGrade.pointsPossible = Convert.ToInt32(possibleTxt.Text);
studentGrade.pointsEarned = Convert.ToInt32(earnedTxt.Text);
if (studentGrade.alreadyExistsg())
{
AssignmentError.Text = "This student has already submitted " + studentGrade.assignmentName + " for this course.";
}
else
{
if (studentGrade.saveScore())
{
Response.Redirect("StudentList.aspx");
}
else
{
AssignmentError.Text = "Oops! Something went wrong...";
}
}
}
This is Grades.cs class:
public void calculate()
{
string letterGrade;
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.GetScores", conn);
cmd.Parameters.Add(new SqlParameter("#enrollmentId", courseId));
cmd.CommandType = System.Data.CommandType.StoredProcedure;
using (conn)
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
Error Here----> double totalEarned = Convert.ToDouble(reader["totalEarned"]);
double totalPossible = Convert.ToDouble(reader["totalPossible"]);
double score = Math.Round(totalEarned / totalPossible, 2) * 100;
if (score >= 90)
{
letterGrade = "A";
}
else if (score < 90 && score >= 80)
{
letterGrade = "B";
}
else if (score < 80 && score >= 70)
{
letterGrade = "C";
}
else if (score < 70 && score >= 60)
{
letterGrade = "D";
}
else
{
letterGrade = "F";
}
update(letterGrade);
conn.Close();
conn.Dispose();
}
}
public Boolean saveScore()
{
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand add = new SqlCommand("dbo.AddScore", conn);
add.Parameters.Add("#enrollmentId", System.Data.SqlDbType.Int);
add.Parameters["#enrollmentId"].Value = enrollmentId;
add.Parameters.Add("#assignmentName", System.Data.SqlDbType.Char);
add.Parameters["#assignmentName"].Value = assignmentName;
add.Parameters.Add("#pointsPossible", System.Data.SqlDbType.Int);
add.Parameters["#pointsPossible"].Value = pointsPossible;
add.Parameters.Add("#pointsEarned", System.Data.SqlDbType.Int);
add.Parameters["#pointsEarned"].Value = pointsEarned;
add.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
int outputval = add.ExecuteNonQuery();
conn.Close();
conn.Dispose();
if (outputval == -1)
{
calculate();
return true;
}
else
{
return false;
}
}
private void update(string letterGrade)
{
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.UpdateGrade", conn);
cmd.Parameters.Add(new SqlParameter("#enrollmentId", enrollmentId));
cmd.Parameters.Add(new SqlParameter("#letterGrade", letterGrade));
cmd.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
Here is my ASP:
<asp:Label ID="Label1" runat="server" Text="Select Semester"></asp:Label><br />
<asp:DropDownList ID="DDSemesters" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DDSemesters_SelectedIndexChanged" DataTextField="semesterName" DataValueField="semesterId"></asp:DropDownList><br />
<asp:Label ID="CoursesLbl" runat="server" Text="Select Course" Visible="false"></asp:Label><br />
<asp:DropDownList visible="false" ID="DDCourses" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DDCourses_SelectedIndexChanged" DataTextField="courseName" DataValueField="courseId"></asp:DropDownList><br />
<asp:Label ID="StudentLbl" runat="server" Text="Select Student" Visible="false"></asp:Label><br />
<asp:DropDownList visible="false" ID="DDStudents" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DDStudents_SelectedIndexChanged" DataTextField="fullName" DataValueField="enrollmentId"></asp:DropDownList><br />
<div id="assignmentInfoDiv" runat="server" visible="false" style="margin-top: 50px;">
<asp:Label ID="studentName" runat="server" Text="Student Name" ></asp:Label>
<asp:Label ID="AssignmentLbl" runat="server" Text="Assignment"></asp:Label><br />
<asp:DropDownList ID="AssignmentList" runat="server">
<asp:ListItem Text="Assignment 1"></asp:ListItem>
<asp:ListItem Text="Assignment 2"></asp:ListItem>
<asp:ListItem Text="Assignment 3"></asp:ListItem>
<asp:ListItem Text="Assignment 4"></asp:ListItem>
<asp:ListItem Text="Assignment 5"></asp:ListItem>
<asp:ListItem Text="Assignment 6"></asp:ListItem>
<asp:ListItem Text="Assignment 7"></asp:ListItem>
<asp:ListItem Text="Assignment 8"></asp:ListItem>
<asp:ListItem Text="Assignment 9"></asp:ListItem>
<asp:ListItem Text="Assignment 10"></asp:ListItem>
<asp:ListItem Text="Quiz 1"></asp:ListItem>
<asp:ListItem Text="Quiz 2"></asp:ListItem>
<asp:ListItem Text="Midterm Project"></asp:ListItem>
<asp:ListItem Text="Final Project"></asp:ListItem>
</asp:DropDownList>
<asp:Label ID="earnedLbl" runat="server" Text="Points Earned:"></asp:Label>
<asp:TextBox ID="earnedTxt" runat="server"></asp:TextBox>
<asp:Label ID="possibleLbl" runat="server" Text="Points Possible:"></asp:Label>
<asp:TextBox ID="possibleTxt" runat="server"></asp:TextBox>
<asp:Button ID="SaveScore" runat="server" Text="Save" OnClick="SaveScore_Click" />
<asp:Label ID="AssignmentError" runat="server"></asp:Label>
</div>
What am I doing wrong?

Dynamically Populating text boxes from drop down not working

I am trying to get two text boxes to populate when a drop down list has it's value selected (and I want the data in the text boxes to change when the selection is changed without the page reloading), I wrote some code compiling what I have gathered from other questions like this, but for some reason its just not working here is my CS.
public partial class UsersFormPage : Page
{
protected void userddlistedit_SelectedIndexChanged(object sender, EventArgs e)
{
FillBoxes(userddlistedit.SelectedValue);
}
private void FillBoxes(string HR_ID)
{
// Create a new dataset object
DataSet dt = new DataSet();
// Create SqlConnection
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source=SQL2008R2SRV;Initial Catalog=employeetrainingtracking;Integrated Security=True";
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
// Set the connection on the sql command object
cmd.Connection = conn;
cmd.CommandText = "select * from users where HR_ID='" + HR_ID + "'";
using (SqlDataAdapter adap = new SqlDataAdapter(cmd))
{
adap.Fill(dt);
}
}
}
if (dt.Tables[0].Rows.Count > 0)
{
usernameedit.Text = dt.Tables[0].Rows[0]["Username"].ToString(); //Where column name us the Fields for your Table that you wanted to display in the TextBoxes
passwordedit.Text = dt.Tables[0].Rows[0]["Password"].ToString();
}
}
}
And here is the part of my page it affects:
<li class="form-row text-row">
<label>User:</label>
<asp:DropDownList ID="userddlistedit" runat="server" CssClass="text-input-dds" DataSourceID="personnelsql" DataTextField="HR_ID" DataValueField="HR_ID" AutoPostBack="True" OnSelectedIndexChanged="userddlistedit_SelectedIndexChanged" />
</li>
<li class="form-row text-input-row">
<label>Username:</label>
<asp:TextBox name="usernameedit" type="text" class="text-input-lg required" id="usernameedit" runat="server" AutoPostBack="True" />
</li>
<li class="form-row text-input-row">
<label>Password:</label>
<asp:TextBox name="passwordedit" type="text" class="text-input-lg required" id="passwordedit" runat="server" AutoPostBack="True" />
</li>
I cannot seem to figure out why its not working.
This is the data source for my drop down list:
<asp:SqlDataSource ID="personnelsql" runat="server"
ConnectionString="<%$ ConnectionStrings:employeetrainingtrackingConnectionString %>"
SelectCommand="SELECT * FROM personnel ORDER BY HR_ID">
</asp:SqlDataSource>
I figured out what I was missing, so I am posting the code below so people can use it:
Here is the code that goes on the CS page:
protected void userddlistedit_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM users ";
selectSQL += "WHERE HR_ID='" + userddlistedit.SelectedItem.Value + "'";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
usernameedit.Text = reader["Username"].ToString();
passwordedit.Text = reader["Password"].ToString();
accessleveledit.SelectedValue = reader["AccessLevel"].ToString();
reader.Close();
lblResults.Text = "";
}
finally
{
con.Close();
}
}
This is the code in the actual aspx page, I added two things:
-I added the DropDownExtender
-I added the triggers (after the but before the tag
<li class="form-row text-row">
<label>User:</label>
<asp:DropDownList ID="userddlistedit" runat="server" CssClass="text-input-dds" AutoPostBack="True" OnSelectedIndexChanged="userddlistedit_SelectedIndexChanged"></asp:DropDownList>
</li>
<li class="form-row text-input-row">
<label>Username:</label>
<asp:TextBox name="usernameedit" type="text" class="text-input-lg required" id="usernameedit" runat="server"></asp:TextBox>
<asp:DropDownExtender ID="ExtenderUserEdit" DropDownControlID="userddlistedit" Enabled="true" TargetControlID="usernameedit" runat="server"></asp:DropDownExtender>
<asp:RequiredFieldValidator runat="server" ID="ValidateUsernameEdit" ControlToValidate="usernameedit" ErrorMessage="Username is required" Display="dynamic" ValidationGroup="EditSection">*</asp:RequiredFieldValidator>
</li>
<li class="form-row text-input-row">
<label>Password:</label>
<asp:TextBox name="passwordedit" type="text" class="text-input-lg required" id="passwordedit" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="ValidatePasswordEdit" ControlToValidate="passwordedit" ErrorMessage="Password is required" Display="dynamic" ValidationGroup="EditSection">*</asp:RequiredFieldValidator>
</li>
.....
<Triggers>
<asp:AsyncPostBackTrigger ControlID="userddlistedit" EventName="SelectedIndexChanged" />
</Triggers>
I also changed the way I got my data for the drop down list to the following (added in the CS page):
private void UsersListDD()
{
userddlist.Items.Clear();
userddlistedit.Items.Clear();
userddlistdelete.Items.Clear();
string selectSQL = "SELECT * FROM personnel";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["FirstName"] + " " + reader["LastName"];
newItem.Value = reader["HR_ID"].ToString();
userddlist.Items.Add(newItem);
userddlistedit.Items.Add(newItem);
userddlistdelete.Items.Add(newItem);
}
reader.Close();
}
finally
{
con.Close();
}
}
Hopefully, this helps someone.

updatepanel trigger cause fullpostback instead partial postback

I want partial postback(asyncpostback) instead fullpostback.but it's not working. Dynamically created checkbox where check or unchecked checkbox cause fullpostback
but it should be asyncpostback.Here is my code.....
<asp:CheckBoxList ID="chkList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="chkList_SelectedIndexChanged"
ClientIDMode="AutoID">
</asp:CheckBoxList>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblMessage" runat="server" Visible="false"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="chkList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
C# code:
private static readonly string constring = ConfigurationManager.ConnectionStrings["ConnectionStrRead"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(constring);
SqlCommand com = new SqlCommand("Select * from Category");
com.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
int dtRows = dt.Rows.Count;
List<string> itemList = new List<string>();
for (int i = 0; i < dtRows; i++)
{
//itemList = new List<string>();
string item = dt.Rows[i]["CategoryName"].ToString() + "(" + dt.Rows[i]["CreateUser"].ToString() + ")";
itemList.Add(item);
}
chkList.DataSource = itemList.ToArray();
chkList.DataBind();
con.Close();
}
}
protected void chkList_SelectedIndexChanged(object sender, EventArgs e)
{
lblMessage.Visible = true;
lblMessage.Text = string.Empty;
foreach (ListItem item in chkList.Items)
{
if (item.Selected)
{
lblMessage.Text += item.Text + "<br/>";
}
}
}
Can u check your scriptmanager EnablePartialRendering attribute. It must be EnablePartialRendering="true"
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableViewState="False" EnablePartialRendering="true" EnableScriptGlobalization="true" > </asp:ScriptManager>
If problem is not about that u can try add AsyncPostBackTrigger in code behind
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(chkList);

Binding sqldatareader to gridview c#

I am creating an application for a asp.net class that I am taking. One of the pages in the application needs to allow a user to search for a specific student via last name or user ID. When the student is found the page should display the students data and his/her class schedule.
I have gotten everything to work except for the class schedule. The approach I have taken (as we learned in class) was to get the query results via the SqlDataReader and bind it to a GridView. This is done in showStudentSchedule().
The query in this function returns the correct results when I test it against the DB I created, but the grid view displaying a students schedule doesn't show up on the page.
//StudentInformation.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="StudentInformation.aspx.cs" Inherits="StudentInformation" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<p>
<asp:Label ID="Label6" runat="server" Text="Search by Last Name: "></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
</asp:DropDownList>
</p>
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:Label ID="Label2" runat="server"></asp:Label>
<br />
<asp:Label ID="Label3" runat="server"></asp:Label>
<br />
<asp:Label ID="Label4" runat="server"></asp:Label>
<br />
<asp:Label ID="Label5" runat="server"></asp:Label>
<asp:Panel ID="Panel1" runat="server">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</asp:Panel>
</asp:Content>
//StudentInformation.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.SqlClient;
public partial class StudentInformation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string userStr = TextBox1.Text;
int userInt;
bool isNum = int.TryParse(userStr, out userInt);
string sqlSelectFindUserByName;
if (isNum)
sqlSelectFindUserByName = string.Format("SELECT LastName FROM Personal_Info JOIN Students ON Personal_Info.ID = Students.Student_ID WHERE Personal_Info.ID = '{0}'", userInt);
else
sqlSelectFindUserByName = string.Format("SELECT LastName FROM Personal_Info JOIN Students ON Personal_Info.ID = Students.Student_ID WHERE Personal_Info.LastName LIKE '%{0}%'", userStr);
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand commandFindUserByName = new SqlCommand(sqlSelectFindUserByName, connection);
connection.Open();
SqlDataReader readerFindUserByName = commandFindUserByName.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("Please make a selection");
while (readerFindUserByName.Read())
DropDownList1.Items.Add(readerFindUserByName["LastName"].ToString());
if (DropDownList1.Items.Count == 2)
DropDownList1.SelectedIndex = 1;
DropDownList1_SelectedIndexChanged(null, null);
connection.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string nameLast = DropDownList1.SelectedItem.Value;
displayStudent(nameLast);
}
private void displayStudent(String nameLast)
{
clearStudentLabel();
int userInt;
bool isNum = int.TryParse(nameLast, out userInt);
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sqlSelectFindUserInfoByName;
sqlSelectFindUserInfoByName = string.Format("SELECT ID, FirstName, LastName, City, Phone FROM Personal_Info WHERE LastName LIKE '%{0}%'", nameLast);
SqlCommand commandFindUserInfo = new SqlCommand(sqlSelectFindUserInfoByName, connection);
connection.Open();
SqlDataReader readerFindUserInfo = commandFindUserInfo.ExecuteReader();
int i = 0;
while (readerFindUserInfo.Read())
{
Label1.Text = "Student ID: " + readerFindUserInfo["ID"].ToString();
Label2.Text = "First name: " + readerFindUserInfo["FirstName"].ToString();
Label3.Text = "Last name: " + readerFindUserInfo["LastName"].ToString();
Label4.Text = "City: " + readerFindUserInfo["City"].ToString();
Label5.Text = "Phone: " + readerFindUserInfo["Phone"].ToString();
}
connection.Close();
showStudentSchedule(userInt);
}
private void showStudentSchedule(int id)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sqlSelectFindUserInfoByName = string.Format("SELECT Class_Schedule.Section_ID, Class_Schedule.Course_ID, Class_Schedule.Days, Class_Schedule.Time, CASE WHEN Personal_Info.FirstName IS NULL THEN 'Staff' ELSE (Personal_Info.LastName + Personal_Info.FirstName) END AS Name FROM Class_Schedule JOIN Student_Enrollment ON Class_Schedule.Section_ID = Student_Enrollment.Section_ID JOIN Personal_Info ON Class_Schedule.Instructor_ID = Personal_Info.ID WHERE Student_Enrollment.Student_ID = {0}", id);
SqlCommand commandFindUserInfo = new SqlCommand(sqlSelectFindUserInfoByName, connection);
connection.Open();
SqlDataReader readerFindUserInfo = commandFindUserInfo.ExecuteReader();
GridView1.DataSource = readerFindUserInfo;
GridView1.DataBind();
/*
string connectionString = "Data Source=LocalHost;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=sa_0001";
string commandString = "Select * from Customers";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(commandString);
conn.Open();
command.Connection = conn;
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = reader;
GridView1.DataBind();
*/
}
private void clearStudentLabel()
{
Label1.Text = "";
Label2.Text = "";
Label3.Text = "";
Label4.Text = "";
Label5.Text = "";
}
}
Try this out:
SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand command = new SqlCommand(sqlSelectFindUserByName);
connection.Open();
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = reader;
GridView1.DataBind();

Categories

Resources