Fetching and displaying tables on database - c#

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();
}
}

Related

Data does not exist for row/column when selectindexchange on Dropdownlist when clicked on dropdownlist.item.insert as empty position on dropdownlist

When I'm choosing additional (empty) position on Dropdownlist created by DropDownList.Item.Insert whole application is terminated.
if (!Page.IsPostBack)
{
DropDownList4.Items.Add(new ListItem("", ""));
DropDownList4.AppendDataBoundItems = true;
String strConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\projects.accdb";
String strQuery = "select * from projects";
OleDbConnection con = new OleDbConnection(strConnString); ;
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList4.DataSource = cmd.ExecuteReader();
DropDownList4.DataTextField = "Project_name";
DropDownList4.DataValueField = "ID";
DropDownList4.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\projects.accdb";
string strQuery = "select * from projects where" + " ID = #ID";
OleDbConnection con = new OleDbConnection(strConnString);
OleDbCommand cmd = new OleDbCommand();
cmd.Parameters.AddWithValue("#ID", DropDownList4.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
OleDbDataReader myreader;
try
{
con.Open();
myreader = cmd.ExecuteReader();
myreader.Read();
TextBox12.Text = myreader["Project_name"].ToString();
TextBox2.Text = myreader["Owner"].ToString();
myreader.Close();
}
finally
{
con.Close();
}
}
As I'm thinking the reason is that the empty value does not exist in DB (but it is just created every time on Page_load by DropDownList4.Items.Add(new ListItem("", ""))). How to exclude from checking in DB first empty position on DropDownList?
Edited:
...
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList4.DataSource = cmd.ExecuteReader();
if (DropDownList4.SelectedItem.Value == null || DropDownList4.SelectedItem == null)
{
}
DropDownList4.DataTextField = "Project_name";
DropDownList4.DataValueField = "ID";
DropDownList4.DataBind();
}
Still does not working
Edited:
string selected = DropDownList4.SelectedItem.Text;
if (string.IsNullOrEmpty(selected))
{
}
Now - It's working :)
You need (and want to) add the blank dropdown row AFTER you fill the dropdown.
So, say we have this markup:
<asp:DropDownList ID="DropDownList1" runat="server"
Height="26px" Width="207px" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
DataValueField="ID"
DataTextField="HotelName"
>
</asp:DropDownList>
And I DO suggest that you put the DataValue/Text settings in the control - really no need or advantage to putting that code in code behind.
And we don't need (or want) to re-load or re-insert the extra blank dropdown choice each time - so load the dropdown ONLY one time (the PostBack = false in page load as you attempted is correct).
So, we will select a hotel, and then pull that ONE database row for additional information - shove into a few text boxes as your code example does.
I suggest this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strSQL =
"SELECT ID, HotelName FROM tblHotels ORDER BY HotelName";
OleDbCommand cmdSQL = new OleDbCommand(strSQL);
DropDownList1.DataSource = MyRstP(cmdSQL);
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("- Select.. -", "0"));
}
}
DataTable MyRstP(OleDbCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB))
{
cmdSQL.Connection = conn;
using (cmdSQL)
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string HotelPK = DropDownList1.SelectedItem.Value as string;
string strSQL = "SELECT * FROM tblHotels where ID = #ID";
OleDbCommand cmdSQL = new OleDbCommand(strSQL);
cmdSQL.Parameters.Add("#ID", OleDbType.Integer).Value = HotelPK;
DataTable rstData = MyRstP(cmdSQL);
if (rstData.Rows.Count > 0)
{
DataRow OneRow = rstData.Rows[0];
TextBox1.Text = OneRow["HotelName"].ToString();
txtTaxRate.Text = OneRow["HotelTax"].ToString();
}
}
We also assume and have AutoPostBack = true for the drop list to fire each time we change it.

to clear the data of datagridview

I have a tabcontrol, it has 9 tabpage collection each tabpage has a datagridview and a searchbox.
private void txtsrchesd_TextChanged(object sender, EventArgs e)
{
if (txtsrchesd.Text == "")
{
}
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM esd_view where department like '" + txtsrchesd.Text + "%' order by department ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgesd.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
}
private void txtsrchope_TextChanged(object sender, EventArgs e)
{
if (txtsrchope.Text == "")
{
}
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM operations_view where department like '" + txtsrchope.Text + "%' order by department ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgoper.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
}
The output of the other datagridview appears on the other datagridview , how can I clear the output of the datagridview as I clear what I type on my searchbox
hope you understand , thank you for the help
When you are checking with:
{
if (txtsrchope.Text != "")
{}
.....
}
In the else part you don't need to fire the same query as when:
txtsrchop.text ==""
You can replace your else part by this code:
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM operations_view ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgoper.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}

How to display SQL search results in a datagrid using WPF

private void Button_Click(object sender, RoutedEventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.Open();
com.Connection = sc;
string sql;
{
sql = "SELECT FROM WolfAcademyForm WHERE [Forename] == 'txtSearch.Text';";
{
grdSearch.ItemsSource = sql;
sc.Close();
}
This is the code that I have, When I press the search button nothing shows up... Can someone please help me with this problem, I don't get any errors
Problems:
SQL query is not right:
It should be like SELECT * FROM TABLENAME.
In WHERE clause [Forename] == 'txtSearch.Text', == should = and Textbox value should be concatenated using +.
Fixed Code:
private void Button_Click(object sender, RoutedEventArgs e)
{
string sConn = #"Data Source=MYDS;Initial Catalog=MyCat;
User ID=MyUser;Password=MyPass;";
using(SqlConnection sc = new SqlConnection(sConn))
{
sc.Open();
string sql = "SELECT * FROM WolfAcademyForm WHERE [Forename]= #Forename";
SqlCommand com = new SqlCommand(sql, sc);
com.Parameters.AddWithValue("#Forename", txtSearch.Text);
using(SqlDataAdapter adapter = new SqlDataAdapter(com))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}
}
}
Use this
using (SqlConnection con = new SqlConnection(ConString))
{
CmdString = "SELECT FROM WolfAcademyForm WHERE [Forename] == " + txtSearch.Text + ";"
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Employee");
sda.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}

Search and display in gridview

I've been working on this one since someone teaches me to use gridview to display my search result.
My problem is, I can't even make it work, when I click or hit the search button, nothing happen. I have:
-1 textbox for last name
-2 dropdownlist for the province and city
-and a search(trigger)button
Here's what I've done so far:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
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)
{
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();
}
private void BindGridView(string field)
{
DataTable dt = new DataTable();
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
try
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_accredited_providers WHERE DOCTOR_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);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
}
// NO RECORDS FOUND
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
BindGridView(txtName.Text.Trim());
}
}
I'm new to this, please assist me. Thanks!
You are not using the field string variable that you are passing to BindGridView and you are mismanaging your SQL parameters (adding the same parameter twice and assigning a DropDown object as a parameter value).
You are adding the same parameter twice.
To fix this, remove this line: comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
You are not using the field variable.
To fix this, change this line
param.Value = ddlProvince; // Note: You are assigning a dropdown OBJECT as the value here!
to
param.Value = field;
in your BindGridView function.

Calendar to DataGrid

I really can't seem to nail down what I need to accomplish my task. I have a DataGrid in asp.net in VS2010 this displays data from a SQL database , in one of these fields is a "StartDate".
Also I have a simple Calendar running . What I would like is to be able to update my DataGrid by passing it the selected date and using that as the "StartDate" to call a selection on the DataGrid , so only records with that start date will appear.
I have looked on-line but the examples are very old or are a bit confusing .
If anyone can layout the steps (if possible sample code) involved to achieve this i would be grateful or any resources or examples you have come across though I have searched for a while, hence the post!.
Thanks.
What i have currently is
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=PC88;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
else
{
// CalendarChange();
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=PC88;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
}
protected void CalendarDRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
// If the month is CurrentMonth
if (!e.Day.IsOtherMonth)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
if ((dr["Start"].ToString() != DBNull.Value.ToString()))
{
DateTime dtEvent = (DateTime)dr["Start"];
if (dtEvent.Equals(e.Day.Date))
{
e.Cell.BackColor = Color.PaleVioletRed;
}
}
}
}
//If the month is not CurrentMonth then hide the Dates
else
{
e.Cell.Text = "";
}
}
private void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
myda = new SqlDataAdapter("Select * from Bookings where Start ='" + Calendar1.SelectedDate.ToString() + "'", mycn);
dsSelDate = new DataSet();
myda.Fill(dsSelDate, "AllTables");
if (dsSelDate.Tables[0].Rows.Count == 0 )
{
GridView1.Visible = false;
}
else
{
GridView1.Visible = true;
GridView1.DataSource = dsSelDate;
GridView1.DataBind ();
}
}
}
What am i doing wrong?.
EDIT__
Finally it works , Here is my code if anyone has similar issue/requirement.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!IsPostBack)
{
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=BBC-PC-S054683;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
else
{ // CalendarChange();
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=PC-Name;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
BindGrid();
}
}
private DataTable GetRecords()
{
SqlConnection conn = new SqlConnection(strConnection);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from Bookings";
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
return objDs.Tables[0];
}
public void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
String Date = Calendar1.SelectedDate.ToLongDateString();
SqlConnection con = new SqlConnection(strConnection);//put connection string here
SqlCommand objCommand = new SqlCommand("SELECT * FROM Bookings where Date = '" + Date + "'", con);//let MyTable be a database table
con.Open();
SqlDataReader dr = objCommand.ExecuteReader();
GridView.DataSource = dr;
GridView.DataBind();
}
You need to filter your DataGridView.
try
{
myDataSet = new DataSet();
myDataSet.CaseSensitive = true;
DataAdapter.SelectCommand.Connection = myConnection;
DataAdapter.TableMappings.Clear();
DataAdapter.TableMappings.Add("Table", "TableName");
DataAdapter.Fill(myDataSet);
myDataView = new DataView(myDataSet.Tables["TableName"], "TIMESTAMP >= '" +
Convert.ToDateTime(fromDate) + "' AND TIMESTAMP <= '" +
Convert.ToDateTime(toDate) + "'", "TIMESTAMP", DataViewRowState.CurrentRows);
dgv.DataSource = myDataView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
TIMESTAMP is a column in my DataGridView.
Note: This is just a code snippet!

Categories