I'm currently making a voting app on C# Windows Form.
So I made a SQL query to count how many people voted for a specific candidate that will be displayed on textBox4
private void button1_Click(object sender, EventArgs e)
{
string idcan = textBox3.Text;
string score = textBox4.Text;
Connection con = new Connection();
SqlConnection sqlcon = con.Sambung();
sqlcon.Open();
string cek = "select count (ID_Candidate) as Score from DataVote where ID_Candidate = #idcan";
using (sqlcon)
{
SqlCommand com = new SqlCommand(cek, sqlcon);
com.Parameters.Add("idcan", SqlDbType.VarChar, 5).Value = score;
}
try
{
sqlcon.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How to display the results of the above SQL query to textBox4?
private void button1_Click(object sender, EventArgs e)
{
string idcan = textBox3.Text;
string score = textBox4.Text;
Connection con = new Connection();
SqlConnection sqlcon = con.Sambung();
sqlcon.Open();
string cek = "select count (ID_Candidate) as Score from DataVote where ID_Candidate = #idcan";
using (sqlcon)
{
SqlCommand com = new SqlCommand(cek, sqlcon);
com.Parameters.Add("idcan", SqlDbType.VarChar, 5).Value = score;
}
try
{
sqlcon.Open();
textBox4.Text=Convert.ToString(com.ExecuteScalar());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You can actually do this code:
private void button1_Click(object sender, EventArgs e)
{
string idcan = textBox3.Text;
string score = textBox4.Text;
Datatable dt = new DataTable();
Connection con = new Connection();
SqlConnection sqlcon = con.Sambung();
SqlCommand com ;
sqlcon.Open();
string cek = "select count (ID_Candidate) as Score from DataVote where ID_Candidate = #idcan";
using(sqlcon)
{
using(com = new SqlCommand(cek, sqlcon))
{
sqlcon.Open();
com.Parameter.Add("#idcan",score );
SqlDataAdapter da = new SqlDataAdapter(com);
da.File(dt);
if(dt.Rows.Count > 0)
{
textBox4.Text = dt.Rows[0]["Score"].ToString();
}
}
}
}
Since your SELECT statement returns one row with one column, you can use ExecuteScalar to get it.
textBox4.Text = com.ExecuteScalar().ToString();
And your code needs a little bit refactoring like;
using(SqlConnection sqlcon = con.Sambung())
using(SqlCommand com = sqlcon.CreateCommand())
{
com.CommandText = "select count (ID_Candidate) as Score from DataVote where ID_Candidate = #idcan";
com.Parameters.Add("#idcan", SqlDbType.VarChar, 5).Value = score;
sqlcon.Open();
textBox4.Text = com.ExecuteScalar().ToString();
}
By the way, I strongly suspect your ID_Candidate column should be some numeric type instead of VarChar based on it's name.
Expand your question: If your query return as a table (many columns, many rows), you can use this code below. Similar for case return single value.
//Create class to store result value
public class ClassName
{
public string Col1 { get; set; }
public int Col2 { get; set; }
}
// In query code
ClassName[] allRecords = null;
SqlCommand command = ...; // your code
using (var reader = command.ExecuteReader())
{
var list = new List<ClassName>();
while (reader.Read())
list.Add(new ClassName {Col1 = reader.GetString(0), Col2 = reader.GetInt32(1)});
allRecords = list.ToArray();
}
Related
They're must be a minor error somewhere in my code that im not seeing as to why on my web page , the gridview only outputs one row when i know the query works/
Both rows from management studio
Only one row in ASP page
heres my c#
string AdminID = Request.QueryString["ID"];
string AdminsCurrentLocation = Request.QueryString["Location"];
//retrieve admin location
try
{
string connectionString = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
//
// Create new SqlConnection object.
//
using (SqlConnection connection5 = new SqlConnection(connectionString))
{
connection5.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM [DB_A05369_WATERQ].[dbo].[S_CONTROL] WHERE LOGIN = '" + AdminID + "'", connection5))
{
//
// Invoke ExecuteReader method.
//
using (SqlDataReader reader2 = command.ExecuteReader())
{
reader2.Read();
TempLocationIdbox.Text = (reader2["ALL_LOCATION_ACCESS"].ToString());
}
}
connection5.Close();
}
}
catch (Exception ex) { }
if(TempLocationIdbox.Text == "Y")
{
string strSQLconnection = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("SELECT DISTINCT ACT.ROW_ID , ACT.CREATED , MEM.FIRST_NAME , MEM.LAST_NAME , LOC.NAME , CAT.NAME , SER.NAME , EMP.FIRST_NAME , EMP.LAST_NAME , SER.DURATION , ACT.CASH , COS.NAME , ACT.COMMENTS FROM " +
"S_ACTIVITY ACT, S_LOCATION LOC, S_CATEGORY CAT, S_EMPLOYEE EMP, S_SERVICE SER, S_COST_CODE COS, S_MEMBER MEM " +
"WHERE ACT.EMPLOYEE_ID = EMP.ROW_ID AND ACT.SERVICE_ID = SER.ROW_ID AND ACT.CATEGORY_ID = CAT.ROW_ID AND ACT.COST_CODE_ID = COS.ROW_ID AND ACT.LOCATION_ID = LOC.ROW_ID AND ACT.MEMBER_ID = MEM.ROW_ID", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
//collect rowID
string retrievedROWID = "";
if (reader.HasRows)
{
reader.Read();
string temp1 = reader["ROW_ID"].ToString();
retrievedROWID = temp1;
GridView1.DataSource = reader;
GridView1.DataBind();
}
sqlConnection.Close();
}
else if (TempLocationIdbox.Text == "N")
{
string strSQLconnection1 = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection1 = new SqlConnection(strSQLconnection1);
SqlCommand sqlCommand1 = new SqlCommand("SELECT * FROM S_LOCATION WHERE NAME = '" + AdminsCurrentLocation + "'", sqlConnection1);
sqlConnection1.Open();
string locationrowID = "";
SqlDataReader reader12 = sqlCommand1.ExecuteReader();
if (reader12.HasRows)
{
reader12.Read();
locationrowID = reader12["ROW_ID"].ToString();
}
sqlConnection1.Close();
string strSQLconnection = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("SELECT DISTINCT ACT.ROW_ID , ACT.CREATED , MEM.FIRST_NAME , MEM.LAST_NAME , LOC.NAME , CAT.NAME , SER.NAME , EMP.FIRST_NAME , EMP.LAST_NAME , SER.DURATION , ACT.CASH , COS.NAME , ACT.COMMENTS FROM "+
"S_ACTIVITY ACT, S_LOCATION LOC, S_CATEGORY CAT, S_EMPLOYEE EMP, S_SERVICE SER, S_COST_CODE COS, S_MEMBER MEM "+
"WHERE ACT.EMPLOYEE_ID = EMP.ROW_ID AND ACT.SERVICE_ID = SER.ROW_ID AND ACT.CATEGORY_ID = CAT.ROW_ID AND ACT.COST_CODE_ID = COS.ROW_ID AND "+
"ACT.LOCATION_ID = '"+ locationrowID + "' AND ACT.MEMBER_ID = MEM.ROW_ID AND LOC.NAME = '"+ AdminsCurrentLocation + "'", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
//collect rowID
string retrievedROWID = "";
if (reader.HasRows)
{
reader.Read();
string temp1 = reader["ROW_ID"].ToString();
retrievedROWID = temp1;
GridView1.DataSource = reader;
GridView1.DataBind();
}
sqlConnection.Close();
}
What stumps me is that my other query is working fine for the case where TempLocationIdbox.Text == "Y"...
Thanks , any help would be much appreciated.
Instead of using if (reader.HasRows) you need to use while (reader.Read()).Also created some kind of collection for example List<T> and populate it with results inside the while loop.Then outside the loop set the DataSource of the GridView control to point to List<T>.Here's a complete example:
public class Activity
{
public int RowID { get; set; }
public DateTime Created { get; set; }
public string FirstName { get; set; }
}
public partial class UsingSqlDataReader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
this.GetData();
}
}
private void GetData()
{
string cs = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
var activities = new List<Activity>();
using (var con = new SqlConnection(cs))
{
using(var cmd = new SqlCommand("SELECT ACT.ROW_ID,ACT.CREATED,ACT.FIRST_NAME FROM [dbo].[S_ACTIVITY] ACT", con))
{
cmd.CommandType = System.Data.CommandType.Text;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var activity = new Activity();
activity.RowID = Convert.ToInt32(reader["ROW_ID"]);
activity.Created = DateTime.Parse(reader["CREATED"].ToString());
activity.FirstName = Convert.ToString(reader["FIRST_NAME"]);
activities.Add(activity);
}
}
}
}
GridView1.DataSource = activities;
GridView1.DataBind();
}
}
Output:
A better solution would be to put your in-line query in a stored proc and execute the stored proc.
You could also bring it in a dataset and bind the gridview with that. but that is completely your choice.
In-line queries are very error prone and results could be unpredictable hence refrain using that.
I have a database table with 3 columns firstname, Lastname and age. In my C# Windows application I have 3 textboxes called textbox1... I made my connectivity to my SQL Server using this code:
SqlConnection con = new SqlConnection("Data Source = .;
Initial Catalog = domain;
Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tablename", con);
I'd like to get values from my database; if I give a value in textbox1 it has to match the values in the database and retrieve other details to the corresponding textboxes.
I tried this method but it's not working:
cmd.CommandText = "select * from tablename where firstname = '" + textBox1.Text + "' ";
How can I do it to retrieve all the other values to the textboxes?
public Person SomeMethod(string fName)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Person matchingPerson = new Person();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from Employees where FirstName=#fName";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#Fname", fName);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
matchingPerson.firstName = oReader["FirstName"].ToString();
matchingPerson.lastName = oReader["LastName"].ToString();
}
myConnection.Close();
}
}
return matchingPerson;
}
Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +"" part opens you up to SQL injection.
I've changed this to:
"Select * from Employees where FirstName=#fName"
oCmd.Parameters.AddWithValue("#fname", fName);
So what this block of code is going to do is:
Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided.
If that is the case, that person will be stored in a Person object (see below in my answer for the class).
If there is no match, the properties of the Person object will be null.
Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you.
If you want to be able to store this data, you can add them to a List<Person> .
Person class to make it cleaner:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
Now to call the method:
Person x = SomeMethod("John");
You can then fill your textboxes with values coming from the Person object like so:
txtLastName.Text = x.LastName;
create a class called DbManager:
Class DbManager
{
SqlConnection connection;
SqlCommand command;
public DbManager()
{
connection = new SqlConnection();
connection.ConnectionString = #"Data Source=. \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
} // constructor
public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
{
bool returnvalue = false;
try
{
command.CommandText = "select * from TableName where firstname=#firstname and lastname=#lastname";
command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname;
connection.Open();
SqlDataReader reader= command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lastname = reader.GetString(1);
firstname = reader.GetString(2);
age = reader.GetString(3);
}
}
returnvalue = true;
}
catch
{ }
finally
{
connection.Close();
}
return returnvalue;
}
then double click the retrieve button(e.g btnretrieve) on your form and insert the following code:
private void btnretrieve_Click(object sender, EventArgs e)
{
try
{
string lastname = null;
string firstname = null;
string age = null;
DbManager db = new DbManager();
bool status = db.GetUsersData(ref surname, ref firstname, ref age);
if (status)
{
txtlastname.Text = surname;
txtfirstname.Text = firstname;
txtAge.Text = age;
}
}
catch
{
}
}
To retrieve data from database:
private SqlConnection Conn;
private void CreateConnection()
{
string ConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
Conn = new SqlConnection(ConnStr);
}
public DataTable getData()
{
CreateConnection();
string SqlString = "SELECT * FROM TableName WHERE SomeID = #SomeID;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
Conn.Close();
}
return dt;
}
You can use this simple method after setting up your connection:
private void getAgentInfo(string key)//"key" is your search paramter inside database
{
con.Open();
string sqlquery = "SELECT * FROM TableName WHERE firstname = #fName";
SqlCommand command = new SqlCommand(sqlquery, con);
SqlDataReader sReader;
command.Parameters.Clear();
command.Parameters.AddWithValue("#fName", key);
sReader = command.ExecuteReader();
while (sReader.Read())
{
textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
//["LastName"] the name of your column you want to retrieve from DB
textBoxAge.Text = sReader["age"].ToString();
//["age"] another column you want to retrieve
}
con.Close();
}
Now you can pass the key to this method by your textBoxFirstName like:
getAgentInfo(textBoxFirstName.Text);
we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields
class Db
{
private readonly static string ConnectionString =
ConfigurationManager.ConnectionStrings
["DbConnectionString"].ConnectionString;
public static List<string> GetValuesFromDB(string LocationCode)
{
List<string> ValuesFromDB = new List<string>();
string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
$"from [CustomerLocations] where LocationCode='{LocationCode}';";
using (SqlConnection Locationconnection =
new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
try
{
Locationconnection.Open();
SqlDataReader Locationreader = command.ExecuteReader();
while (Locationreader.Read())
{
for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
{
ValuesFromDB.Add(Locationreader[i].ToString());
}
}
Locationreader.Close();
return ValuesFromDB;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
hope this might helpful
Note: you guys need connection string (in our case
"DbConnectionString")
DataTable formerSlidesData = new DataTable();
DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
if (formerSlidesData.Rows.Count > 0)
{
DataRow rowa = formerSlidesData.Rows[0];
cabinet = Convert.ToInt32(rowa["cabinet"]);
box = Convert.ToInt32(rowa["box"]);
drawer = Convert.ToInt32(rowa["drawer"]);
}
I have created comboBox and filled with one column, after I choose item from the combobox I would like to show other column in the textboxs so I wrote code to make it happen but what if I want to choose column from another table I mean I would like to show couple of columns from two different table in the textbox when I hit the combobox
Here is my code:
private void comboLname_SelectedIndexChanged(object sender, EventArgs e)
{
string conn = "Data Source=srv-db-02;Initial Catalog=rmsmasterdbtest;Persist Security Info=True;User ID=test;Password=*******";
string Query = "select * from rmsmasterdbtest.dbo.customer where LastName= '" + comboLname.Text + "' ;";
SqlConnection Myconn = new SqlConnection(conn);
SqlCommand cmdDataBase = new SqlCommand(Query, Myconn);
SqlDataReader Reader;
try
{
Myconn.Open();
Reader = cmdDataBase.ExecuteReader();
while (Reader.Read())
{
string ID = Reader.GetInt32(Reader.GetOrdinal("ID")).ToString();
string AccountNuber = Reader.GetString(Reader.GetOrdinal("AccountNumber"));
//string Time = Reader.GetString(Reader.GetOrdinal("Time"));
// string Deposit = Reader.GetString(Reader.GetOrdinal("Deposit"));
string sstatus = Reader.GetString(Reader.GetOrdinal("status"));
string slastname = Reader.GetString(Reader.GetOrdinal("lastname"));
txtid.Text = ID;
txtacnum.Text = AccountNuber;
//txttime.Text = Time;
//txtdeposit.Text = Deposit;
txtstatus.Text = sstatus;
txtlname.Text = slastname;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
Myconn.Close();
}
}
I have a database table with 3 columns firstname, Lastname and age. In my C# Windows application I have 3 textboxes called textbox1... I made my connectivity to my SQL Server using this code:
SqlConnection con = new SqlConnection("Data Source = .;
Initial Catalog = domain;
Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tablename", con);
I'd like to get values from my database; if I give a value in textbox1 it has to match the values in the database and retrieve other details to the corresponding textboxes.
I tried this method but it's not working:
cmd.CommandText = "select * from tablename where firstname = '" + textBox1.Text + "' ";
How can I do it to retrieve all the other values to the textboxes?
public Person SomeMethod(string fName)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Person matchingPerson = new Person();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from Employees where FirstName=#fName";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#Fname", fName);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
matchingPerson.firstName = oReader["FirstName"].ToString();
matchingPerson.lastName = oReader["LastName"].ToString();
}
myConnection.Close();
}
}
return matchingPerson;
}
Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +"" part opens you up to SQL injection.
I've changed this to:
"Select * from Employees where FirstName=#fName"
oCmd.Parameters.AddWithValue("#fname", fName);
So what this block of code is going to do is:
Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided.
If that is the case, that person will be stored in a Person object (see below in my answer for the class).
If there is no match, the properties of the Person object will be null.
Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you.
If you want to be able to store this data, you can add them to a List<Person> .
Person class to make it cleaner:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
Now to call the method:
Person x = SomeMethod("John");
You can then fill your textboxes with values coming from the Person object like so:
txtLastName.Text = x.LastName;
create a class called DbManager:
Class DbManager
{
SqlConnection connection;
SqlCommand command;
public DbManager()
{
connection = new SqlConnection();
connection.ConnectionString = #"Data Source=. \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
} // constructor
public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
{
bool returnvalue = false;
try
{
command.CommandText = "select * from TableName where firstname=#firstname and lastname=#lastname";
command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname;
connection.Open();
SqlDataReader reader= command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lastname = reader.GetString(1);
firstname = reader.GetString(2);
age = reader.GetString(3);
}
}
returnvalue = true;
}
catch
{ }
finally
{
connection.Close();
}
return returnvalue;
}
then double click the retrieve button(e.g btnretrieve) on your form and insert the following code:
private void btnretrieve_Click(object sender, EventArgs e)
{
try
{
string lastname = null;
string firstname = null;
string age = null;
DbManager db = new DbManager();
bool status = db.GetUsersData(ref surname, ref firstname, ref age);
if (status)
{
txtlastname.Text = surname;
txtfirstname.Text = firstname;
txtAge.Text = age;
}
}
catch
{
}
}
To retrieve data from database:
private SqlConnection Conn;
private void CreateConnection()
{
string ConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
Conn = new SqlConnection(ConnStr);
}
public DataTable getData()
{
CreateConnection();
string SqlString = "SELECT * FROM TableName WHERE SomeID = #SomeID;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
Conn.Close();
}
return dt;
}
You can use this simple method after setting up your connection:
private void getAgentInfo(string key)//"key" is your search paramter inside database
{
con.Open();
string sqlquery = "SELECT * FROM TableName WHERE firstname = #fName";
SqlCommand command = new SqlCommand(sqlquery, con);
SqlDataReader sReader;
command.Parameters.Clear();
command.Parameters.AddWithValue("#fName", key);
sReader = command.ExecuteReader();
while (sReader.Read())
{
textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
//["LastName"] the name of your column you want to retrieve from DB
textBoxAge.Text = sReader["age"].ToString();
//["age"] another column you want to retrieve
}
con.Close();
}
Now you can pass the key to this method by your textBoxFirstName like:
getAgentInfo(textBoxFirstName.Text);
we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields
class Db
{
private readonly static string ConnectionString =
ConfigurationManager.ConnectionStrings
["DbConnectionString"].ConnectionString;
public static List<string> GetValuesFromDB(string LocationCode)
{
List<string> ValuesFromDB = new List<string>();
string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
$"from [CustomerLocations] where LocationCode='{LocationCode}';";
using (SqlConnection Locationconnection =
new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
try
{
Locationconnection.Open();
SqlDataReader Locationreader = command.ExecuteReader();
while (Locationreader.Read())
{
for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
{
ValuesFromDB.Add(Locationreader[i].ToString());
}
}
Locationreader.Close();
return ValuesFromDB;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
hope this might helpful
Note: you guys need connection string (in our case
"DbConnectionString")
DataTable formerSlidesData = new DataTable();
DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
if (formerSlidesData.Rows.Count > 0)
{
DataRow rowa = formerSlidesData.Rows[0];
cabinet = Convert.ToInt32(rowa["cabinet"]);
box = Convert.ToInt32(rowa["box"]);
drawer = Convert.ToInt32(rowa["drawer"]);
}
I'm just starting out at asp.net c# and I have been given a task to generate the available doctors upon the given values in a drop-down list.
I have 3 drop-down lists, (1)PROVINCE, (2)CITY, (3)SPECIALIZATION and a search button.
After the user selects the values of 3 drop-down lists and hits the search button it will print a table containing the available doctor.
I know that the key is on the search button, but I don't exactly know what to put under the search button. Can you help me out please?
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
if (!IsPostBack)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_city WHERE PROVINCE_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlCity.DataBind();
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_city");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("select distinct emed_accredited_providers.SPECIALIZATION from emed_accredited_providers inner join emed_doctors_hospitals on emed_accredited_providers.DOCTOR_CODE = emed_doctors_hospitals.DOCTOR_CODE where CITY_CODE =#ccode", conn);
comm.Parameters.AddWithValue("#ccode", ddlCity.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#ccode";
param.Value = ddlCity;
comm.Parameters.Add(param);
}
ddlSpec.DataSource = dt;
ddlSpec.DataTextField = "SPECIALIZATION";
ddlSpec.DataValueField = "SPECIALIZATION";
ddlSpec.DataBind();
}
protected void btnDocs_Click(object sender, EventArgs e)
{
}
}
}
string query = string.Empty;
if (ddlProvince.SelectedIndex != -1)
{
query = query + " and PROVINCE_CODE=" + ddlProvince.SelectedValue;
}
if (ddlCity.SelectedIndex != -1)
{
query = query + " and CITY_CODE=" + ddlProvince.SelectedValue;
}
if (ddlSpec.SelectedIndex != -1)
{
query = query + " and SPECIALIZATION=" + ddlProvince.SelectedValue;
}
string tQuery = "Select * from Doc";
if (query.Length > 0)
{
query = query.Remove(0, 4);
tQuery = tQuery + query;
}
// Exeucate -- tQuery
// Modify table name or field name.
get the selected values from the drop down list
pass the selected values to your search function. (It depends on your logic, I mean if user select values from only one drop down, from only two drop down your search query may differ).
get the return values from your search function and bind it to your table (grid view)
Also have a look at the DropDownList.SelectedIndex Property
to bind the gridview you can do something similar to this
private void BindGrid ()
{
var dt = new DataTable();
var connection = new SqlConnection(YOUR CONNECTION);
try
{
connection.Open();
var query = "YOUR SEARCH QUERY";
var sqlCmd = new SqlCommand(query, connection);
var sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
//
}
finally
{
connection.Close();
}
}