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.
Related
Class code:
using System.Data.SqlClient;
namespace WebApplication5
{
public class Class1
{
public int ID;
public string nem;
public int salar;
public void ReadIMP(int id )
{
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=emp;Integrated Security=True");
string Query = "select * from employee where Id = '" + id + "' ";
SqlCommand cmd = new SqlCommand(Query, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ID = (int)reader["Id"];
nem = (string)reader["name"];
salar = (int)reader["salary"];
}
reader.Close();
conn.Close();
}
}
}
aspx.cs code:
protected void Read_IMP(object sender, EventArgs e)
{
try
{
Class1 class1 = new Class1();
class1.ReadIMP(Convert.ToInt16(TextBox1.Text));
}
catch (Exception ex)
{
LabelEX.Text = ex.Message;
}
}
aspx code:
<div>
enter the id of employees :
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
Id of employees is
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
name of employees is
<asp:Label ID="Label2" runat="server"></asp:Label>
<br />
salary of employee is :
<asp:Label ID="Label3" runat="server"></asp:Label>
<asp:Button ID="Button4" runat="server" Text="Search" OnClick="Read_IMP" />
<br />
<asp:Label ID="LabelEX" runat="server" Text="Label"></asp:Label>
.............................................................................
I'am using method in class to retrieve data from database and calling the method in aspx.cs page
I want to filling these attributes: ID , nem , salar into Label1 , Label2 ,Label3 haw can i do it
From your code, you already fill data in fields, let those data fill on your aspx control directly
Class1 class1 = new Class1();
class1.ReadIMP(Convert.ToInt16(TextBox1.Text));
Label1.Text = (string)class1.ID;
Label2.Text = class1.nem;
Label3.Text = (string)class1.salar;
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?
hi i tried to display image from sql table to gridview but its not displaying this is my code to bind gridview with sql table records.....
When the user login , the user login photo should display thats y i am trying
the image already stored in database but there is an ISSUE to retrive the image from database to gridview
PostBookChat.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblsession.Text = "Welcome" + Convert.ToString(Session["UName"]);
sessionimage();
}
}
private void sessionimage()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
try
{
int EmpID = (int)Session["EmpID"];
SqlDataAdapter Adp = new SqlDataAdapter("select EmpID,Photo from TBL_PBLogin where EmpID='" + EmpID + "'", con);
DataTable Dt = new DataTable();
con.Open();
Adp.Fill(Dt);
gridviewphoto.DataSource = Dt;
gridviewphoto.DataBind();
con.Close();
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
PostBookChat.aspx
<body>
<form id="form1" runat="server">
<div>
<div id="header">
<img src="Image/book.png" height="60" width="140" style ="margin-left:0px;float:left;"/>
<div id="login">
<b><asp:Label ID="lblsession" runat="server" ForeColor="white" CssClass="label"></asp:Label>
<asp:GridView ID="gridviewphoto" runat="server" AutoGenerateColumns="false" BackColor="#CC3300" ForeColor="Black" ShowHeader="false" GridLines="None">
<Columns>
<asp:TemplateField ControlStyle-Width="100" ControlStyle-Height="100">
<ItemTemplate>
<asp:Image ID="Image" runat="server" ImageUrl='<%# "~/Handler.ashx?id=" + Eval("EmpID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnlogout" runat="server" Text="Sign Out" CssClass="myButton" OnClick="btnlogout_Click"/>
</div>
</div>
</body>
Handler.ashx
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["EmpID"] == null) return;
string connStr = ConfigurationManager.AppSettings["connect"].ToString();
string pictureId = context.Request.QueryString["EmpID"];
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Photo FROm TBL_PBLogin WHERE EmpID = #EmpId", conn))
{
cmd.Parameters.Add(new SqlParameter("#EmpID", pictureId));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
reader.Read();
context.Response.ContentType = "image/png";
context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("Photo")]);
reader.Close();
}
}
}
}
DataBase
EmpID (PK,int notnull) (1,1)
UName(varchar(255),notnull)
Password(varchar(255),notnull)
Photo(image,null)
I am making an application about article publication. I have 2 tables
"artikulli"
id int Unchecked
tema varchar(250) Checked
abstrakti text
data_publikimit date
path varchar(350)
keywords varchar(350)
kategoria_id int
departamenti_id int
"kategorite"
id int Unchecked
emertimi varchar(350)
I want to display in a dropdown list all values of field "emertimi" and when the user selects one value to save id of that value in table "artikulli".
I have done the following, but I have the problem with syntax because I am using DATALIST.
public partial class AddArticle : System.Web.UI.Page
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
try
{
if (!IsPostBack)
{
Bind();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
public void Bind()
{
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
protected void datalist2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox txtTema = e.Item.FindControl("txtTema") as TextBox;
TextBox txtAbstrakti = e.Item.FindControl("txtAbstrakti") as TextBox;
TextBox txtData = e.Item.FindControl("txtData") as TextBox;
TextBox txtKeywords = e.Item.FindControl("txtKeywords") as TextBox;
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection conn = new SqlConnection(connection);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "Insert into artikulli(tema,abstrakti,data_publikimit,path,keywords,kategoria_id) values (#tema,#abstrakti,#data,#filename,#keywords,#kategoria)";
command.Parameters.Add(new SqlParameter("#tema", txtTema.Text));
command.Parameters.Add(new SqlParameter("#abstrakti", txtAbstrakti.Text));
command.Parameters.Add(new SqlParameter("#data", txtData.Text));
command.Parameters.Add(new SqlParameter("#keywords", txtKeywords.Text));
command.Parameters.Add(new SqlParameter("#kategoria", drpdKategoria.SelectedValue));
FileUpload FileUploadArtikull = (FileUpload)e.Item.FindControl("FileUploadArtikull");
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise se file qe lejohet eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
//add parameters
command.Parameters.AddWithValue("#filename", filename);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Bind();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni ngarkuar asnje artikull');", true);
}
}
}
AddArtikull.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AddArtikull.aspx.cs" Inherits="AddArticle" MasterPageFile="~/MasterPage2.master" %>
<asp:Content ID="content2" ContentPlaceholderID=ContentPlaceHolder2 runat="server">
<asp:DataList ID="datalist2" runat="server"
onitemcommand="datalist2_ItemCommand" >
<FooterTemplate>
<section id="main" class="column" runat="server" style="width:900px;">
<article class="module width_full" style="width:900px;">
<header><h3 style="text-align: center">Shto Artikull </h3></header>
<div id="Div1" class="module_content" runat="server">
<asp:Label ID="Label1" runat="server" style="font-weight: 700">Tema</asp:Label>
<fieldset>
<asp:TextBox ID="txtTema" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorTema" runat="server"
ControlToValidate="txtTema" Display="Dynamic"
ErrorMessage="Kjo fushe eshte e nevojshme" style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset><br />
<asp:Label ID="Label6" runat="server" style="font-weight: 700">Abstrakti</asp:Label>
<fieldset>
<asp:TextBox ID="txtAbstrakti" style="height:250px;" Textmode="Multiline" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorAbstrakti" runat="server"
ControlToValidate="txtAbstrakti" ErrorMessage="Kjo fushe eshte e nevojshme"
style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset>
<asp:Label ID="lblData" runat="server" style="font-weight: 700">Data e Publikimit</asp:Label>
<fieldset>
<asp:TextBox ID="txtData" runat="server"></asp:TextBox>
</fieldset>
<asp:Label ID="lblKeywords" runat="server" style="font-weight: 700">Keywords</asp:Label>
<fieldset>
<asp:TextBox ID="txtKeywords" runat="server"></asp:TextBox>
</fieldset>
<br />
<asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
<div>
<asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Insert"
/>
</div><br />
<strong>Ngarko Artikull</strong><br />
<asp:FileUpload ID="FileUploadArtikull" runat="server" /><br />
<br />
<asp:Button ID="btnInsert" runat="server" CommandName="Insert" Text="Shto" />
</div>
</article>
</section>
</FooterTemplate>
</asp:DataList>
</asp:Content>
It shows this error:
Compiler Error Message: CS0103: The name 'e' does not exist in the
current context
In this line:
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
In your bind method you are calling an object e that doesn't exist. If the dropdownlist isn't inside a bound element, you can just reference the front code directly, e.g.
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
without finding the control as long as it is runat="server"
UPDATE
Okay, so you need to add an OnItemCreated event in your datalist
OnItemCreated="datalist2_OnItemCreated"
Then in that method you need this
protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
}
That will work for if you only have the footer, if you add an itemtemplate then you just need to get rid of the check for the footer and on each item creation grab that dropdownlist for that item
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();