Getting one data from another table in DropownList with AutoPostBack - c#

I have a Customer table --> CustomerNumber and CustomerName columns
I have a Sales table --> CustomerName columns
I have a Label (represent CustomerNumber) and a DropDownList (represent CustomerName)
I getting to DropDownList Sales table --> CustomerName with SqlDataSource.
I want automaticly (with AutoPostBack) filling Label with CustomerNumber which CustomerName selected in DropDownList
Example SQL:
select A.CustomerNumber
from Customer A, Sales B
where B.CustomerName = DropDownList1.SelectedItems.Value
I'm thinking like this.
How can i do that?
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}

Try this
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if(-1 != DropDownList1.SelectedIndex)
{
using(SqlConnection connection = new SqlConnection("connectionString"))
{
connection.Open();
using(SqlCommand command = new SqlCommand("SELECT A.CUSTOMERNUMBER FROM CUSTOMER A, SALES B WHERE B.CUSTOMERNAME = #CustomerName"))
{
command.Connection = connection;
command.Parameters.AddWithValue("#CustomerName", DropDownlist1.SelectedValue.ToString());
this.Label1.Text = command.ExecuteScalar().ToString();
}
}
}
}
Hope it works. Disclaimer : I didn't tested the code

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedName = DropDownList1.SelectedValue;
string sqlQuery = "select A.CustomerNumber from Customer A, Sales B where B.CustomerName = '" + DropDownList1.SelectedValue + "'";
// pass you sql query to command object and call execute scalar method
label1.Text = dbCommand.ExecuteScalar().ToString();
}
What do ExecuteScalar do?

Related

My list session is not retriving the right value

I have a list to save the orders the client had selected and i wanted to pass the values on the list to other page so i was trying to use
HttpContext.Current.Session["list"] = MySelected;
but I am not getting the values in my other page.
order page:
protected void ButtonCreate_Click(object sender, EventArgs e)
{
string MyPkList = string.Join(",", MySelected);
SqlCommand cmdSQLCount = new SqlCommand("select Count(*) from [EncomendaTEMP] where No_ IN(" + MyPkList + ")", con);
cmdSQLCount.Connection.Open();
int qtd = 0;
SqlDataReader reader = cmdSQLCount.ExecuteReader();
while (reader.Read())
qtd = reader.GetInt32(0);
if (qtd > 0)
{
HttpContext.Current.Session["list"] = MySelected;
Response.Redirect("Booking.aspx", false);
}
else
{
Response.Write("<h2> Nenhum registo encontrado! </h2>");
}
Booking page:
protected void Page_Load(object sender, EventArgs e)
{
var list = HttpContext.Current.Session["list"];
Response.Write("<h2> PK = "+list+" </h2>");
}
returns:
To get join value of element in List<string>, try:
var list = HttpContext.Current.Session["list"] as List<string>;
string items = string.Join(",", list);
from #Chetan Ranpariya 's comment.

DropDownLists Issue ASP.NET

I really have a serious issues with postback, I have 3 dropdownlists, the first one contain data from a database, it's the countries, the second is the same but for the cities who depends the selected value on the first dropdownlist which is the countries, and the third dropdownlist is the airlines who depends on the selected value of the second dropdownlist which is the cities.
So the first two dropdownlists work perfectly, but the third dropdownlist will never work even with autopostback true and false, it will always refresh on to the first value and I wrote if(!IsPostback) so I really I'm frustrated about this issue.
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;
using System.Configuration;
using System.Data;
using System.IO;
namespace Hijazi_Airlines
{
public partial class Book : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["HAirlines"].ConnectionString);
protected void Page_Init(object sender, EventArgs e)
{
if (Session["Username"] != null)
{
Sign.Text = "Sign Out";
}
else
{
}
gather_countries();
gather_cities();
gather_Tocountries();
gather_Tocities();
}
private void gather_date()
{
try
{
string query = "SELECT Depart FROM Flights where Airlines_id=" + Airlin.SelectedValue;
SqlCommand sqlcmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
SqlDataReader reader = sqlcmd.ExecuteReader();
reader.Read();
Response.Write(reader[0].ToString());
sqlcon.Close();
}
catch
{
}
sqlcon.Close();
}
private void gather_cities()
{
FromCit.Items.Clear();
string cities = "select * from Cities where country_id = " + FromCount.SelectedValue;
CountriesAndCities(cities, FromCit);
}
private void gather_Tocities()
{
ToCit.Items.Clear();
string cities = "select * from Cities where country_id = " + To.SelectedValue;
CountriesAndCities(cities, ToCit);
}
private void gather_countries()
{
string Countries = "select * from Countries order by country desc";
CountriesAndCities(Countries, FromCount);
}
private void gather_Tocountries()
{
string Countries = "select * from Countries order by country desc";
CountriesAndCities(Countries, To);
}
private void CountriesAndCities(string query, DropDownList dp)
{
SqlCommand sqlcmdC = new SqlCommand(query, sqlcon);
sqlcon.Open();
SqlDataReader reader = sqlcmdC.ExecuteReader();
while (reader.Read())
{
ListItem item = new ListItem();
item.Text = reader[1].ToString();
item.Value = reader[0].ToString();
dp.Items.Insert(0, item);
}
sqlcon.Close();
}
protected void Hom_Click(object sender, EventArgs e)
{
Response.Redirect("Home.aspx");
}
protected void SignIN_Click1(object sender, EventArgs e)
{
if (Sign.Text == "Sign Out")
{
Session.RemoveAll();
Session.Abandon();
Sign.Text = "Sign In";
}
else
{
Response.Redirect("Login.aspx");
}
}
protected void Contact_Click(object sender, EventArgs e)
{
Response.Redirect("Contact.aspx");
}
protected void FromCount_SelectedIndexChanged(object sender, EventArgs e)
{
gather_cities();
}
protected void To_SelectedIndexChanged(object sender, EventArgs e)
{
gather_Tocities();
}
protected void Airlin_SelectedIndexChanged(object sender, EventArgs e)
{
gather_date();
}
}
}
Problem is here:
string query = "SELECT Depart FROM Flights where Airlines_id=" + Airlin.SelectedValue;
You said that the third dropdownlist is the airlines who depends on the selected value of the second dropdownlist which is the cities. But in the above code you are selecting the value of third dropdown which makes no sense as it doesn't have any value.
So instead of above code, change the id value to this:
string query = "SELECT Depart FROM Flights where Airlines_id=" + YourCityDropDownId.SelectedValue;
Check this and let me know.
Your problem is permanently recreate ddl.
gather_Tocountries();
gather_Tocities();
Well, for solution this problem, you need after created your ddls set selected value for ToCit and To ddl.
ToCit.SelectedValue = yourValue; //Something like this;
But code which you wrote is not productive, because you each time call database
if you wanna init your ddl after select in prev, just call your method
CountriesAndCities in SelectedIndexChanged. First init you can do in pageInit or pageLoad but with use if(isPostBack){your first ddl init}
for example
PageLoad(){
if(IsPostBack){
string Countries = "select * from Countries order by country desc";
CountriesAndCities(Countries, FromCount);
}
}
For other ddl the same
then
protected void FromCount_SelectedIndexChanged(object sender, EventArgs e)
{
gather_cities();
}

i have to search from the database "employee details" for the employee name using parameterised

I have a gridview(gridview1) which where I have initially displayed my database using sqlDataSource(ID:sqlDataSource1). I have provided a search button to the user from where he can search for an employee by typing his name. On clicking on that button, the gridview should display only the matching results.
this is the function I have performed on button click. Is there any command that I am missing out?
the error shown is: Must declare the scalar variable "#TextBoxSearchParameter".
TextBoxSearch is the ID of a textBox.
EmployeeDetails is a database that has employeeID and the EmployeeName
protected void ButtonSearch_Click(object sender, EventArgs e)
{
SqlDataSource1.SelectCommand = "select * from EmployeeDetails where
EmployeeName like #TextBoxSearchParameter";
SqlDataSource1.SelectParameters.Add("#TextBoxSearchParameter",
TextBoxSearch.Text + "%");
GridView1.DataBind();
}
It should display the record of all the employees starting with the name as entered by the user on the gridview1.
Try This
protected void ButtonSearch_Click(object sender, EventArgs e)
{
SqlDataSource1.SelectCommand = "select * from EmployeeDetails where
EmployeeName like #TextBoxSearchParameter %";
SqlDataSource1.SelectParameters.AddWithValue("#TextBoxSearchParameter",
TextBoxSearch.Text);
GridView1.DataBind();
}
Try this
SqlDataSource1.SelectCommand = "select * from EmployeeDetails where EmployeeName like '% #TextBoxSearchParameter %' ";
SqlDataSource1.SelectParameters.Add("#TextBoxSearchParameter",
TextBoxSearch.Text);
try this
protected void ButtonSearch_Click(object sender, EventArgs e)
{
SqlDataSource1.SelectCommand = "select * from EmployeeDetails where EmployeeName like '%#TextBoxSearchParameter%'"; //query modified
SqlDataSource1.SelectParameters.Add("#TextBoxSearchParameter", TextBoxSearch.Text); // modified the around TextBoxSearch.Text
GridView1.DataBind();
}

When I using the delete button , I get a error message....How to solve this?

protected void Button1_Click1(object sender, EventArgs e)
{
string year = tb_year.Text;
string gross = tb_gross.Text;
string rating = DropDownList2.SelectedValue;
string director = tb_director.Text;string sel = DropDownList1.SelectedValue;
string query = "UPDATE MovieList SET ReleaseYear=#YearValue," +
"Gross=#GrossValue, Rating=#RatingValue," +
"Director=#DirectorValue WHERE Rank=#SelValue";
System.Data.OleDb.OleDbCommand ocmd =
new System.Data.OleDb.OleDbCommand(query,
new System.Data.OleDb.OleDbConnection(CSTR));
ocmd.Parameters.AddWithValue("#YearValue", year);
ocmd.Parameters.AddWithValue("#GrossValue", gross);
ocmd.Parameters.AddWithValue("#RatingValue", rating);
ocmd.Parameters.AddWithValue("#DirectorValue", director);
ocmd.Parameters.AddWithValue("#SelValue", sel);
ocmd.Connection.Open();
ocmd.ExecuteNonQuery();
ocmd.Connection.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
string year = tb_year.Text;
string gross = tb_gross.Text;
string rating = DropDownList2.SelectedValue;
string director = tb_director.Text;
string sel = DropDownList1.SelectedValue;
string query = "DELETE FROM MovieList WHERE Movie=" + DropDownList1.SelectedItem.Text + "'";
System.Data.OleDb.OleDbCommand ocmd =
new System.Data.OleDb.OleDbCommand(query,
new System.Data.OleDb.OleDbConnection(CSTR));
ocmd.Parameters.AddWithValue("#YearValue", year);
ocmd.Parameters.AddWithValue("#GrossValue", gross);
ocmd.Parameters.AddWithValue("#RatingValue", rating);
ocmd.Parameters.AddWithValue("#DirectorValue", director);
ocmd.Parameters.AddWithValue("#SelValue", sel);
ocmd.Connection.Open();
ocmd.ExecuteNonQuery(); <<***
ocmd.Connection.Close();
populateDropDowns();
}
}
}
The button 1 is a update button, when I change the value, it can be update the database information and this button can update the information immediate.
But the Delete button, when I delete the information, it will throw an error message:
"OleDbException was unhandled by user code : Additional information:
Syntax error (missing operator) in query expression 'Movie=The Matrix
Revolutions''. in "***".
However, when I open this website again, the information is deleted. How to solve this error message and delete the information immediate??
Do it the same way like you did with your update, use SQL parameters for the where clause. So this code should work:
protected void Button2_Click(object sender, EventArgs e)
{
string sel = DropDownList1.SelectedValue;
// if your selection is empty, abort early
if( sel == null || string.IsNullOrEmpty(sel.Text)) return;
// use a SQL parameter like you did with update
string query = "DELETE FROM MovieList WHERE Movie=#MovieValue";
System.Data.OleDb.OleDbCommand ocmd =
new System.Data.OleDb.OleDbCommand(query,
new System.Data.OleDb.OleDbConnection(CSTR));
// here the selected text for the movie is set to the movie parameter
ocmd.Parameters.AddWithValue("#MovieValue", sel.Text);
ocmd.Connection.Open();
ocmd.ExecuteNonQuery();
ocmd.Connection.Close();
populateDropDowns();
}
string query = "DELETE FROM MovieList WHERE Movie='" + DropDownList1.SelectedItem.Text + "'";
You should change your query with the above, you are missing '

ASP.NET Manual ListBox Filters for GridView

I have multiple ListBoxes as Categories, Departments, Faculties etc. And I have a GridView populated from database (MSSQL) in code-behind. I will use ListBoxes as filters.
For example, when i choose a category from CategoriesListBox, the GridView will show only the entries in this category. And when I also choose a Department, the GridView will show only the entries in selected category and department.
I suppose that I will do it by use of selectedIndexChanged event of ListBoxes. My aspx code is:
public partial class Default : System.Web.UI.Page
{
private string constr = MY_CONNECTION_STRING;
protected void Page_Load(object sender, EventArgs e)
{
FillGridView();
}
protected void FillGridView()
{
string Query = "SELECT * FROM Entry WHERE Category = '" + SelectedCategory +"' AND Department = '" + SelectedDepartment +"'";
SqlConnection conn = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(Query, conn);
try
{
conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write("Hata: " + ex.Message);
}
finally
{
conn.Close();
}
}
protected void CategoriesListBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Here I want to get SelectedCategory value and re-fill GridView
}
protected void DepartmentsListBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Here I want to get SelectedDepartment value and re-fill GridView
}
}
Thanks for help.
you can do it by select from your table where CategoryName =#parameter in your connection string
#parameter is your listbox selectedItem or selected value.
Using your own code, why not pass the category and department to the FillGridView? And if one of those are null it would mean no filter at all. So, something like this:
protected void CategoriesListBox_SelectedIndexChanged(object sender, EventArgs e)
{
FillGridView(lbCategory.SelectedItem.ToString(), lbDepartment.SelectedItem.ToString());
}
The same would be applied on the DepartmentsListBox_SelectedIndexChanged event.
Then change the FillGridView function to:
protected void FillGridView(string SelectedCategory, string SelectedDepartment)
Also, if I may I'd suggest to gather all the table contents at once, save data to an in-memory copy and filter them from said copy, this would enable a much more fast and better user experience imo.
Edit:
if (selectedCategory.Trim() == "")
selectedCategory = "IS NOT NULL";
else
selectedCategory = " = \'" + selectedCategory.Trim() + "\'";
if (selectedDepartment.Trim() == "")
selectedDepartment = "IS NOT NULL";
else
selectedDepartment = " = \'" + selectedDepartment.Trim() + "\'";
string Query = "SELECT * FROM Entry WHERE Category " + SelectedCategory + " AND Department " + SelectedDepartment;
Add it to the beginning of the FillGridView function (this is just a quick & easy hack, not the best solution).

Categories