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.
Related
This is my first question on this site so i apologise in advance if I format it incorrectly.
I am creating a system which should be able to search a database (dataGridView) using multiple checkboxes. I found some code online to search it using 3 checkboxes but am unsure how to extend this. I will need to be able to search using 50+ checkboxes. The following code is executed upon pressing of a search button which will display corresponding rows in my database. I want to know to most efficient way to extend this solution to 50+ checkboxes.
private void button1_Click(object sender, EventArgs e)
{
String filterdata = "";
if (checkBox1.Checked)
{
if (checkBox2.Checked || checkBox3.Checked)
{
filterdata = "'T05A1.1',";
}
else
{
filterdata = "'T05A1.1'";
}
}
if (checkBox2.Checked)
{
if (checkBox3.Checked)
{
filterdata = filterdata + "'C16D6.2',";
}
else
{
filterdata = filterdata + "'C16D6.2'";
}
}
if (checkBox3.Checked)
{
filterdata = filterdata + "'F41E7.3'";
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
//cmd.CommandText = "Select * from Table1 where elegansgeneID ='" + filterdata + "'";
cmd.CommandText = "Select * from Table1 where elegansgeneID in(" + filterdata + ")";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Try this more shorter approach:
private void Button1_Click(object sender, EventArgs e)
{
var values = new List<string>();
if (checkBox1.Checked)
values.Add("'T05A1.1'");
if (checkBox2.Checked)
values.Add("'C16D6.2'");
if (checkBox3.Checked)
values.Add("'F41E7.3'");
// and so on
String filterdata = string.Join(",", values);
...
}
Alexander Petrov's answer is correct.
But if you are getting more than 50 Check boxes then I would suggest you use CheckBoxList. The code becomes more simpler then.
public Form1()
{
InitializeComponent();
List<string> filters = new List<string> { "T05A1.1", "C16D6.2", "F41E7.3" };
checkedListBox1.Items.Clear();
foreach (string filter in filters)
{
checkedListBox1.Items.Add(filter);
}
}
private void button1_Click(object sender, EventArgs e)
{
List<string> selectedFilter = new List<string>();
for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
selectedFilter.Add("'" + checkedListBox1.CheckedItems[i].ToString() + "'");
}
string query = "Select * from Table1 where elegansgeneID in(" + string.Join(",", selectedFilter) + ")";
}
With CheckBoxList, you can just add your filters in the filters List variable and it will generate your list. This will keep your code short as well.
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 '
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).
I want to maintain user control values in view state
I tried but values are removed
Code:
In the below code I read the values from database and load it in user controls,it's working but if I want to add one more user control when click add button those values are removed
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (OleDbCommand cmd = new OleDbCommand("Select * from visa_details where emp_id = '" + empid + "'", DbConnection))
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
OleDbDataReader DR1 = cmd.ExecuteReader();
while (DR1.Read())
{
string visaNumb = DR1[2].ToString();
string visaCountry = DR1[3].ToString();
string visaType = DR1[4].ToString();
string visaEntry = DR1[5].ToString();
string expiryDate = DR1[6].ToString();
expiryDate = DateTime.Parse(expiryDate).ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture);
VisaUserControl userconrol = (VisaUserControl)Page.LoadControl("VisaUserControl.ascx");
userconrol.TextVisaNumber = visaNumb;
userconrol.VisaCountry = visaCountry;
userconrol.VisaType = visaType;
userconrol.VisaEntry = visaEntry;
userconrol.ExpiryDate = expiryDate;
rpt1.Controls.Add(userconrol);
}
}
}
}
Below code is for adding user control when click add button
public List<string> NoOfControls
{
get
{
return ViewState["NoOfControls"] == null ? new List<string>() : (List<string>)ViewState["NoOfControls"];
}
set
{
ViewState["NoOfControls"] = value;
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
GenerateControls();
}
private void GenerateControls()
{
foreach (string i in NoOfControls)
{
VisaUserControl ctrl = (VisaUserControl)Page.LoadControl("VisaUserControl.ascx");
ctrl.ID = i;
this.rpt1.Controls.Add(ctrl);
}
}
protected void btnAddVisa_Click(object sender, EventArgs e)
{
List<string> temp = null;
var uc = (VisaUserControl)this.LoadControl(#"VisaUserControl.ascx");
string id = Guid.NewGuid().ToString();
uc.ID = id;
temp = NoOfControls;
temp.Add(id);
NoOfControls = temp;
rpt1.Controls.Add(uc);
}
In the below image if I click Add More Visa button those values and controls are removed I want to persist those values
Any ideas? Thanks in advance
The fact is that when you click the button, the page does a postback, therefore the part of your code in the Page_Load event inside the if (!IsPostBack) condition is not executed.
This includes the creation of the VisaUserControl, which you are creating dynamically.
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?