Sql where statement not working using asp.net? - c#

To better explain my problem with my personal website project, I would start off with the database that I have created. The table is called guitarItems.
This table is where i get data for displaying images and guitar details in the webpage. In order to do this, I created a method named "GetGuitarItems" to execute and read the sql statements.
public static ArrayList GetGuitarItems(string itemCategory)
{
ArrayList list = new ArrayList();
string query = string.Format("SELECT * FROM guitarItems WHERE brand LIKE '{0}'", itemCategory);
try
{
conn1.Open();
command1.CommandText = query;
SqlDataReader reader = command1.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32(0);
string type = reader.GetString(1);
string brand = reader.GetString(2);
string model = reader.GetString(3);
double price = reader.GetDouble(4);
string itemimage1 = reader.GetString(5);
string itemimage2 = reader.GetString(6);
string description = reader.GetString(7);
string necktype = reader.GetString(8);
string body = reader.GetString(9);
string fretboard = reader.GetString(10);
string fret = reader.GetString(11);
string bridge = reader.GetString(12);
string neckpickup = reader.GetString(13);
string bridgepickup = reader.GetString(14);
string hardwarecolor = reader.GetString(15);
GuitarItems gItems = new GuitarItems(id, type, brand, model, price, itemimage1, itemimage2, description, necktype, body,
fretboard, fret, bridge, neckpickup, bridgepickup, hardwarecolor);
list.Add(gItems);
}
}
finally
{
conn1.Close();
}
return list;
}
Next part is this code where you display the data that you have retrieved from the database.
public partial class Pages_GuitarItems1 : System.Web.UI.Page
{
private string brandType = "Ibanez";
private int x = 0;
protected void Page_Load(object sender, EventArgs e)
{
FillPage();
}
private void FillPage()
{
ArrayList itemList = new ArrayList();
ArrayList itemListPage = new ArrayList();
if (!IsPostBack)
{
itemList = ConnectionClassGuitarItems.GetGuitarItems("%");
}
else
{
itemList = ConnectionClassGuitarItems.GetGuitarItems(brandType);
}
StringBuilder sb = new StringBuilder();
foreach (GuitarItems gList in itemList)
{
itemListPage.Add("GuitarItemsIbanezDetails" + (x + 1) + ".aspx");
sb.Append(
string.Format(
#"
<div class='one-two'>
<a href='{3}' runat='server'><img runat='server' src='{0}'/></a>
<div class='content'>
<div id='label'>{1} {2}</div>
</div>
</div>", gList.ItemImage1, gList.Brand, gList.Model, itemListPage[x]));
x++;
}
lblOutput.Text = sb.ToString();
}
}
Now the problem is its displaying every guitar items in the database. As shown from the code above, what I'm trying to display is only the guitar items with brand "Ibanez" in it. I have my suspicions with the foreach code but atleast for now, the GetGuitarItemsMethod is designed to get only the Ibanez guitar items and the data will be passed on to the ArrayList itemList variable for displaying. And I have also checked the sql statement and it seems correct. Hope you guys can help me on this one.

Change from
if (!IsPostBack)
{
itemList = ConnectionClassGuitarItems.GetGuitarItems("%");
}
else
{
itemList = ConnectionClassGuitarItems.GetGuitarItems(brandType);
}
to
itemList = ConnectionClassGuitarItems.GetGuitarItems(brandType);

Related

C# MySQLDataReader returns column names instead of field values

I am using MySQLClient with a local database. I wrote a method which returns a list of data about the user, where I specify the columns I want the data from and it generates the query dynamically.
However, the reader is only returning the column names rather than the actual data and I don't know why, since the same method works previously in the program when the user is logging in.
I am using parameterised queries to protect from SQL injection.
Here is my code. I have removed parts which are unrelated to the problem, but i can give full code if needed.
namespace Library_application
{
class MainProgram
{
public static Int32 user_id;
static void Main()
{
MySqlConnection conn = LoginProgram.Start();
//this is the login process and works perfectly fine so i won't show its code
if (conn != null)
{
//this is where things start to break
NewUser(conn);
}
Console.ReadLine();
}
static void NewUser(MySqlConnection conn)
{
//three types of users, currently only using student
string query = "SELECT user_role FROM Users WHERE user_id=#user_id";
Dictionary<string, string> vars = new Dictionary<string, string>
{
["#user_id"] = user_id.ToString()
};
MySqlDataReader reader = SQLControler.SqlQuery(conn, query, vars, 0);
if (reader.Read())
{
string user_role = reader["user_role"].ToString();
reader.Close();
//this works fine and it correctly identifies the role and creates a student
Student user = new Student(conn, user_id);
//later i will add the logic to detect and create the other users but i just need this to work first
}
else
{
throw new Exception($"no user_role for user_id - {user_id}");
}
}
}
class SQLControler
{
public static MySqlDataReader SqlQuery(MySqlConnection conn, string query, Dictionary<string, string> vars, int type)
{
MySqlCommand cmd = new MySqlCommand(query, conn);
int count = vars.Count();
MySqlParameter[] param = new MySqlParameter[count];
//adds the parameters to the command
for (int i = 0; i < count; i++)
{
string key = vars.ElementAt(i).Key;
param[i] = new MySqlParameter(key, vars[key]);
cmd.Parameters.Add(param[i]);
}
//runs this one
if (type == 0)
{
Console.WriteLine("------------------------------------");
return cmd.ExecuteReader();
//returns the reader so i can get the data later and keep this reusable
}
else if (type == 1)
{
cmd.ExecuteNonQuery();
return null;
}
else
{
throw new Exception("incorrect type value");
}
}
}
class User
{
public List<string> GetValues(MySqlConnection conn, List<string> vals, int user_id)
{
Dictionary<string, string> vars = new Dictionary<string, string> { };
//------------------------------------------------------------------------------------
//this section is generating the query and parameters
//using parameters to protect against sql injection, i know that it ins't essential in this scenario
//but it will be later, so if i fix it by simply removing the parameterisation then im just kicking the problem down the road
string args = "";
for (int i = 0; i < vals.Count(); i++)
{
args = args + "#" + vals[i];
vars.Add("#" + vals[i], vals[i]);
if ((i + 1) != vals.Count())
{
args = args + ", ";
}
}
string query = "SELECT " + args + " FROM Users WHERE user_id = #user_id";
Console.WriteLine(query);
vars.Add("#user_id", user_id.ToString());
//-------------------------------------------------------------------------------------
//sends the connection, query, parameters, and query type (0 means i use a reader (select), 1 means i use non query (delete etc..))
MySqlDataReader reader = SQLControler.SqlQuery(conn, query, vars, 0);
List<string> return_vals = new List<string>();
if (reader.Read())
{
//loops through the reader and adds the value to list
for (int i = 0; i < vals.Count(); i++)
{
//vals is a list of column names in the ame order they will be returned
//i think this is where it's breaking but im not certain
return_vals.Add(reader[vals[i]].ToString());
}
reader.Close();
return return_vals;
}
else
{
throw new Exception("no data");
}
}
}
class Student : User
{
public Student(MySqlConnection conn, int user_id)
{
Console.WriteLine("student created");
//list of the data i want to retrieve from the db
//must be the column names
List<string> vals = new List<string> { "user_forename", "user_surname", "user_role", "user_status"};
//should return a list with the values in the specified columns from the user with the matching id
List<string> return_vals = base.GetValues(conn, vals, user_id);
//for some reason i am getting back the column names rather than the values in the fields
foreach(var v in return_vals)
{
Console.WriteLine(v);
}
}
}
What i have tried:
- Using getstring
- Using index rather than column names
- Specifying a specific column name
- Using while (reader.Read)
- Requesting different number of columns
I have used this method during the login section and it works perfectly there (code below). I can't figure out why it doesnt work here (code above) aswell.
static Boolean Login(MySqlConnection conn)
{
Console.Write("Username: ");
string username = Console.ReadLine();
Console.Write("Password: ");
string password = Console.ReadLine();
string query = "SELECT user_id, username, password FROM Users WHERE username=#username";
Dictionary<string, string> vars = new Dictionary<string, string>
{
["#username"] = username
};
MySqlDataReader reader = SQLControler.SqlQuery(conn, query, vars, 0);
Boolean valid_login = ValidLogin(reader, password);
return (valid_login);
}
static Boolean ValidLogin(MySqlDataReader reader, string password)
{
Boolean return_val;
if (reader.Read())
{
//currently just returns the password as is, I will implement the hashing later
password = PasswordHash(password);
if (password == reader["password"].ToString())
{
MainProgram.user_id = Convert.ToInt32(reader["user_id"]);
return_val = true;
}
else
{
return_val = false;
}
}
else
{
return_val = false;
}
reader.Close();
return return_val;
}
The problem is here:
string args = "";
for (int i = 0; i < vals.Count(); i++)
{
args = args + "#" + vals[i];
vars.Add("#" + vals[i], vals[i]);
// ...
}
string query = "SELECT " + args + " FROM Users WHERE user_id = #user_id";
This builds a query that looks like:
SELECT #user_forename, #user_surname, #user_role, #user_status FROM Users WHERE user_id = #user_id;
Meanwhile, vars.Add("#" + vals[i], vals[i]); ends up mapping #user_forename to "user_forename" in the MySqlParameterCollection for the query. Your query ends up selecting the (constant) value of those parameters for each row in the database.
The solution is:
Don't prepend # to the column names you're selecting.
Don't add the column names as variables to the query.
You can do this by replacing that whole loop with:
string args = string.Join(", ", vals);

Overwriting of variable in SqlDataReader while-loop

I have read some threads that seem to be similar to this but can't find the fix for my issue, I've not used stack overflow much so pls bear with me
I have a while loop using an SqlDataReader which is pulling information from a DB and putting it into a List for Development Requests as below
public ListOfDevelopmentRequestsModel GetDevRequests(List<SelectListItem> evaluators)
{
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetDevRequests, Conn);
cmd.CommandType = CommandType.StoredProcedure;
ListOfDevelopmentRequestsModel ListOfDevRequests = new ListOfDevelopmentRequestsModel();
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
DateTime requestDate = Convert.ToDateTime(reader["DateCreated"].ToString());
string requestorFirstName = reader["Staff First Name"].ToString();
string requestorLastName = reader["Staff Last Name"].ToString();
string requestorEmailAddress = reader["Staff Email"].ToString();
string solutionName = reader["SolutionName"].ToString();
string solutionDescription = reader["SoultionDescription"].ToString();
string solutionElementName = reader["SolutionElementName"].ToString();
string solutionElementDescription = reader["SolutionElementDescription"].ToString();
string itemToChange = reader["ItemChange"].ToString();
string changeDetails = reader["ChangeDetail"].ToString();
List<SelectListItem> evaluatorList = new List<SelectListItem>(DisplayCurrentEvaluator(evaluators, evaluator));
DevelopmentRequestModel DevRequest = new DevelopmentRequestModel
{
RequestDate = requestDate,
RequestorName = $"{requestorFirstName} {requestorLastName}",
RequestorEmailAddress = requestorEmailAddress,
SolutionName = solutionName,
SolutionDescription = solutionDescription,
SolutionElementName = solutionElementName,
SolutionElementDescription = solutionElementDescription,
ItemToChange = itemToChange,
ChangeDetails = changeDetails,
AccordionHeading = $"{(changeID.PadLeft(4, '0'))} - {requestorFirstName} {requestorLastName} - {itemToChange}"
};
ListOfDevRequests.DevelopmentRequests.Add(DevRequest);
}
Conn.Close();
return ListOfDevRequests;
}
I also have a List for getting Evaluators of the requests
public static List<SelectListItem> GetEvaluators()
{
List<SelectListItem> evaluators = new List<SelectListItem>();
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetEvaluators, Conn);
cmd.CommandType = CommandType.StoredProcedure;
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
evaluators.Add(
new SelectListItem
{
Text = reader["Staff Name"].ToString(),
Value = reader["Staff Code"].ToString(),
});
}
Conn.Close();
return evaluators;
}
Finally I have a List that will pass the above Evaluators List in and the Evaluator that was pulled from the DB: string evaluator = reader["Evaluator"].ToString(); and will set the default value of the select list based on whether the Evaluator name matches the Text value, and set it as the selected select list item.
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
foreach (var item in evaluators)
{
if (item.Text == evaluator)
{
item.Selected = true;
}
else
{
item.Selected = false;
}
}
return evaluators;
}
The issue is that the first item in the loop has the Evaluator "Bill" and "Bill" is selected, and works fine, however the second item in the loop is "John", and when it sets "John" to selected, it replaces "Bill" as the selected value in the first item with "John"
The code has ended up a mess as I have tried multiple different ways to fix but I'm stumped and would appreciate help.
Sorry if the post is formatted poorly to read, I can try to reformat and provide more information if requested.
Cheers
EDITED CODE:
GetDevRequests()
public ListOfDevelopmentRequestsModel GetDevRequests(List<SelectListItem> evaluators)
{
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetDevRequests, Conn);
cmd.CommandType = CommandType.StoredProcedure;
ListOfDevelopmentRequestsModel ListOfDevRequests = new ListOfDevelopmentRequestsModel();
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
List<SelectListItem> evaluatorList = new List<SelectListItem>();
while (reader.Read())
{
string changeID = reader["ChangeID"].ToString();
string evaluator = reader["Evaluator"].ToString();
string status = reader["Status"].ToString();
string priority = reader["Priority"].ToString();
string eliteID = reader["RequestorID"].ToString();
DateTime requestDate = Convert.ToDateTime(reader["DateCreated"].ToString());
string requestorFirstName = reader["Staff First Name"].ToString();
string requestorLastName = reader["Staff Last Name"].ToString();
string requestorEmailAddress = reader["Staff Email"].ToString();
string solutionName = reader["SolutionName"].ToString();
string solutionDescription = reader["SoultionDescription"].ToString();
string solutionElementName = reader["SolutionElementName"].ToString();
string solutionElementDescription = reader["SolutionElementDescription"].ToString();
string itemToChange = reader["ItemChange"].ToString();
string changeDetails = reader["ChangeDetail"].ToString();
evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);
DevelopmentRequestModel DevRequest = new DevelopmentRequestModel
{
ChangeID = (changeID.PadLeft(4, '0')),
Evaluator = evaluator,
Evaluators = evaluatorList,
Status = status,
Priority = priority,
EliteID = eliteID,
RequestDate = requestDate,
RequestorName = $"{requestorFirstName} {requestorLastName}",
RequestorEmailAddress = requestorEmailAddress,
SolutionName = solutionName,
SolutionDescription = solutionDescription,
SolutionElementName = solutionElementName,
SolutionElementDescription = solutionElementDescription,
ItemToChange = itemToChange,
ChangeDetails = changeDetails,
AccordionHeading = $"{(changeID.PadLeft(4, '0'))} - {requestorFirstName} {requestorLastName} - {itemToChange}"
};
ListOfDevRequests.DevelopmentRequests.Add(DevRequest);
}
Conn.Close();
return ListOfDevRequests;
}
DisplayCurrentEvaluator()
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> selectListItems, string selectListDefaultItem)
{
foreach (var item in selectListItems)
{
item.Selected = item.Text == selectListDefaultItem;
}
return selectListItems;
}
The problem is in this line:
List<SelectListItem> evaluatorList = new List<SelectListItem>(DisplayCurrentEvaluator(evaluators, evaluator));
First, this can also be written as
List<SelectListItem> evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);
Your DisplayCurrentEvaluator already returns a correct list, so there is no need to copy it into a new one.
But this is a minor point as you don't use that evaluatorList as far as I can see. In every iteration of that while-loop you are creating a new one (which probably isn't what you want) and then you forget about it. I also don't see where evaluator is set, but that is probably in code you didn't show.
So you will need to generate this list once, outside the loop and keep it (probably in a class-level field or property).
And an extra tip, that DisplayCurrentEvaluator method can also be written as
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
foreach (var item in evaluators)
{
item.Selected = item.Text == evaluator;
}
return evaluators;
}
EDIT after code was shown that set evaluator and used the resulting evaluatorList
Your DisplayCurrentEvaluator updates the original evaluators list and returns it. This effectively results in every evaluatorList pointing to the same list, where the last update wins. So make sure you return a new list.
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
var result = new List<SelectListItem>(evaluators.Count);
foreach (var item in evaluators)
{
result.Add(new SelectListItem { Text = item.Text, Value = item.Value, Selected= item.Text == evaluator};
}
return result;
}
Additionally, declare the evaluatorList (only) inside of the loop.
var evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);

Get data from SQL datebase and return as string

Need help to get the 1st row record and return record as string in the << >> after while() loop.
There are a lot of columns in one row, I'm having a problem to declare it as string st? like usually string st = new string() please help to correct it
Thanks
public string Get_aodIdeal(string SubmittedBy)
{
String errMsg = "";
Guid? rguid = null;
int isOnContract = 0;
int isFreeMM = 0;
string _FileName;
DateTime InstallDateTime = DateTime.Now;
string FileDate = ToYYYYMMDD(DateTime.Now);
errMsg = "Unknown Error.";
SqlConnection conn = null; SqlCommand cmd = null;
string st = null;
conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["iDeal"].ConnectionString);
cmd = new SqlCommand();
string SQL = "select TOP 1 * from table1 Order by SubmittedOn desc";
SqlDataAdapter sqd = new SqlDataAdapter(SQL, conn);
cmd.CommandTimeout = 1200;
conn.Open();
SqlDataReader sqr;
//sqd.SelectCommand.Parameters.Add("#Submitted", SqlDbType.Int).Value = PostID;
sqr = sqd.SelectCommand.ExecuteReader();
while (sqr.Read())
st = new string{
rguid = cmd.Parameters["#rguid"].Value as Guid?,
ridno = int.Parse(sqr["ridno"].ToString()),
SubmittedOn= DateTime.Parse(sqr["SubmittedOn"].ToString()),
SubmittingHost = sqr["SubmittingHost"].ToString(),
ServiceAgreementNo = sqr["ServiceAgreementNo"].ToString(),
DocumentID = sqr["DocumentID"].ToString(),
Source = sqr["Source"].ToString(),
FileName = sqr["FileName"].ToString(),
FileType = sqr["FileType"].ToString(),
FileDate = DateTime.Parse(sqr["FileDate"].ToString()),
InstallTime = DateTime.Parse(sqr["InstallTime"].ToString()),
CalenderCode = cmd.Parameters["CalenderCode"].Value as Guid,
isFreeMM = bool.Parse(sqr["isFreeMM"].ToString()),
isOnContract = bool.Parse(sqr["isOnContract"].ToString()),
isProcessed = bool.Parse(sqr["isProcessed"].ToString()),
ProcessedByFullName = sqr["ProcessedByFullName"].ToString(),
isDelete = bool.Parse(sqr["isDelete"].ToString()),
version = int.Parse(sqr["Version"].ToString()),
LastUpdatedBy = DateTime.Parse(sqr["LastUpdatedBy"].ToString()),
LastUpdatedOn = DateTime.Parse(sqr["LastUpdatedOn"].ToString()),
shopGuid = sqr["shopGuid"].ToString(),
MacID = sqr["MacID"].ToString(),
MSISDN = sqr["MSISDN"].ToString()
}
You can use a StringBuilder for this purpose as like the following:
StringBuilder strBuilder= new StringBuilder();
while (sqr.Read())
{
strBuilder.AppendFormat("PostID : {0}{1}",sqr["PostID"].ToString(),Environment.NewLine);
strBuilder.AppendFormat("dateposted : {0}{1}",sqr["dateposted"].ToString(),Environment.NewLine);
// And so on Build your string
}
Finally the strBuilder.ToString() will give you the required string. But More smarter way is Create a Class with necessary properties and an Overrided .ToString method for display the output.
Let AodIdeal be a class with an overrided ToString() method. And Let me defined it like the following :
public class AodIdeal
{
public int PostID { get; set; }
public string dateposted { get; set; }
public string Source { get; set; }
// Rest of properties here
public override string ToString()
{
StringBuilder ObjectStringBuilder = new StringBuilder();
ObjectStringBuilder.AppendFormat("PostID : {0}{1}", PostID, Environment.NewLine);
ObjectStringBuilder.AppendFormat("dateposted : {0}{1}",dateposted, Environment.NewLine);
ObjectStringBuilder.AppendFormat("Source : {0}{1}", Source, Environment.NewLine);
// and so on
return ObjectStringBuilder.ToString();
}
}
Then you can create an object of the class(let it be objAodIdeal), and make use of its properties instead for the local variables. And finally objAodIdeal.ToString() will give you the required output.
Example usage
AodIdeal objAodIdeal= new AodIdeal();
while (sqr.Read())
{
objAodIdeal.PostID = int.Parse(sqr["PostID"].ToString());
objAodIdeal.dateposted= sqr["dateposted"].ToString();
// assign rest of properties
}
string requiredString= objAodIdeal.ToString();

Looping through an array to add parameters to sql query

I am reading rows out of a text file and storing them to an array. I now need to then loop through the items in every array position. I can loop through the rows in the document but I need to loop through the array values as well.
Here is my code for reading the text file and building the array :
public class people
{
public string name;
public int empid;
public string address;
}
private void read()
{
using (StreamReader sr = new StreamReader(#"E:\test.txt"))
{
while (sr.Peek() >= 0) << This loops through the rows in the text doc
{
string str;
string[] strArray;
str = sr.ReadLine();
strArray = str.Split(',');
people new_people = new people();
new_people.name = strArray[0];
new_people.empid = int.Parse(strArray[1]); // << I need to be able to loop through each of
new_people.address = strArray[2]; // these and add each on to my query string
peoples.Add(new_people);
listBox1.Items.Add(new_people.name + new_people.empid + new_people.address); //< this displays
// the array values
}
}
I need something like this :
foreach (string foo in new_people.name[0] )
{
cmd.Parameters.Add("#1", SqlDbType.VarChar).Value = foo ;
// then do this for every item in the array for that position
cmd.Parameters.Add("#2", SqlDbType.VarChar).Value = (next set of values);
cmd.Parameters.Add("#3", SqlDbType.VarChar).Value = (next set of values);
cmd.ExecuteNonQuery();
}
Creating your own constructor will help you to create instances of Person class (person is singular, people is plural):
public class Person
{
public string Name;
public int Empid;
public string Address;
public Person(string name, int empid, string address)
{
Name = name;
Empid = empid;
Address = address;
}
}
private void read()
{
using (StreamReader sr = new StreamReader(#"E:\test.txt"))
{
while (sr.Peek() >= 0)
{
string str;
string[] strArray;
str = sr.ReadLine();
strArray = str.Split(',');
Person newPerson = new Person(strArray[0], int.Parse(strArray[1]), strArray[2]);
people.Add(newPerson);
listBox1.Items.Add(newPerson.Name + newPerson.Empid + newPerson.Address);
}
}
You can then loop through all names:
int i = 0;
foreach (Person p in people)
cmd.Parameters.Add("#" + (i++), SqlDbType.VarChar).Value = p.Name;
cmd.ExecuteNonQuery();

Getting/Setting Select Box in Literal from ASP.Net Code-Behind

I have the below code that gets added to a literal in my form. How in the code behind to I grab get/set the data from the select = name="populationSelect"....?
protected void PopulatePopulation()
{
StringBuilder sb = new StringBuilder();
StringBuilder sql = new StringBuilder();
// Define sql
sql.Append("SELECT pid, population ");
sql.Append("FROM populations ");
sql.Append("ORDER BY pid ASC ");
using (IDataReader reader = SqlHelper.GetDataReader(sql.ToString()))
{
sb.AppendLine("<div class=\"narrowRes\">Poulation</div><select name=\"populationSelect\" class=\"narrowResSelect\"><option value=\"0\">All populations</option>");
while (reader.Read())
{
int pid = reader.IsDBNull(0) ? -1 : reader.GetInt32(0);
string population = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);
population = population.Trim();
sb.AppendLine(string.Format("<option value=\"{0}\">{1}</option>", pid, population));
}
}
sb.AppendLine("</select>");
ltrlExplorePopulation.Text = sb.ToString();
}
Not easily. Since you're using a literal instead of an asp.net control (like a drop down list), asp.net does not create a control for you to use in the code behind.
That being said you should be able to access the value through the Request parameters.
var value = Request["populationSelect"];
A better solution would be to create a dropdownlist control on the page and databind to it.
if (!IsPostBack)
{
List<ListItem> data = new List<ListItem>();
using (IDataReader reader = SqlHelper.GetDataReader(sql.ToString()))
{
//sb.AppendLine("<div class=\"narrowRes\">Poulation</div><select name=\"populationSelect\" class=\"narrowResSelect\"><option value=\"0\">All populations</option>");
while (reader.Read())
{
int pid = reader.IsDBNull(0) ? -1 : reader.GetInt32(0);
string population = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);
population = population.Trim();
data.Add(new ListItem(population, pid.ToString()));
//sb.AppendLine(string.Format("<option value=\"{0}\">{1}</option>", pid, population));
}
}
DropDownList1.DataSource = data;
DropDownList1.DataBind();
}

Categories