c# asp.net dropdown list select value - c#

I am getting confused with my code and not sure how to implement what I want.
I have two sql tables one that has OfficeID and matching OfficeName and another one that contains user. I have a page that allows a person to edit information about the person. When the page is loaded it supposed to select from the drop down list the current OfficeName of a person whose information is being edited. Thus I have this:
This is probably extremely inefficient and confusing for my level of knowledge of C# and SQL, but none the less I am determined to learn how to do it. What I have currently is Before the creation of the drop down list I get the users Id, then select from the database his corresponding officeID, then while creating the drop down list I check for the OfficeID to correspond to the ones from the other table. If it found the match it will set it as the selected value for the drop down list.
am I on the right track? I need to figure out how to compare SESLoginID = loginID before I convert loginID before hand. Any help?
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Functions;
using HelloApp;
public partial class UserUpdate : Page
{
private Int32 loginID = 0;
protected void Page_Load(object sender, EventArgs e)
{
loginID = Convert.ToInt32(Request.QueryString["SESLoginID"]);
if (!Page.IsPostBack)
{
BindBusinessUnitDDL();
}
}
protected void BindBusinessUnitDDL()
{
SqlConnection conn;
string sql;
SqlCommand cmd;
int error;
conn = Database.DBConnect(out error);
sql = String.Format("SELECT OfficeID FROM SESLogin WHERE SESLoginID = loginID");
cmd = new SqlCommand(sql, conn);
SqlDataReader rdrr = cmd.ExecuteReader();
ListItem office = new ListItem();
office.Value = Convert.ToString(rdrr.GetInt32(0));
Database.DBClose(conn);
sql = String.Format(
"SELECT OfficeID, OfficeName FROM Office");
cmd = new SqlCommand(sql, conn);
SqlDataReader rdr = cmd.ExecuteReader();
DropDownList ddlBusinessUnit = (DropDownList)(this.LoginFormView.FindControl("ddlBusinessUnit"));
while (rdr.Read())
{
ListItem myItem = new ListItem();
myItem.Value = Convert.ToString(rdr.GetInt32(0));
myItem.Text = rdr.GetString(1);
ddlBusinessUnit.Items.Add(myItem);
if(office.Value == myItem.Value){
ddlBusinessUnit.SelectedValue = myItem.Text;
}
}
Database.DBClose(conn);
ddlBusinessUnit.DataBind();
PageUser myUser = new PageUser();
}
A different version of the code where there exists a procedure to return OfficeName using an LoginID. Doesnt work either gives an error:
System.Data.SqlClient.SqlException: Conversion failed when converting the nvarchar value ' SELECT
[OfficeName]
FROM sesuser.SESLogin
INNER JOIN sesuser.Office
ON sesuser.Office.OfficeID = sesuser.SESLogin.OfficeID
WHERE SESLoginID LIKE '287'' to data type int.
public partial class UserUpdate : Page
{
private Int32 loginID = 0;
private String loginIDE = "";
protected void Page_Load(object sender, EventArgs e)
{
loginIDE = Request.QueryString["SESLoginID"];
loginID = Convert.ToInt32(Request.QueryString["SESLoginID"]);
if (!Page.IsPostBack)
{
BindBusinessUnitDDL();
}
}
protected void BindBusinessUnitDDL()
{
SqlConnection connec = null;
SqlCommand cmd = null;
string sqls = "";
int errNum = 0;
connec = Database.DBConnect(out errNum);
if (errNum != 0)
throw new Exception("Database Connection Error.");
sqls = "Login_GetOffice";
cmd = new SqlCommand(sqls, connec);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userID", loginIDE);
string office = (string)cmd.ExecuteScalar();
SqlConnection conn;
string sql;
int error;
conn = Database.DBConnect(out error);
sql = String.Format(
"SELECT OfficeID, OfficeName FROM Office");
cmd = new SqlCommand(sql, conn);
SqlDataReader rdr = cmd.ExecuteReader();
DropDownList ddlBusinessUnit = (DropDownList)(this.LoginFormView.FindControl("ddlBusinessUnit"));
while (rdr.Read())
{
ListItem myItem = new ListItem();
myItem.Value = Convert.ToString(rdr.GetInt32(0));
myItem.Text = rdr.GetString(1);
ddlBusinessUnit.Items.Add(myItem);
if(office == myItem.Text){
myItem.Selected = true;
}
}
Database.DBClose(conn);
ddlBusinessUnit.DataBind();
PageUser myUser = new PageUser();
}

You can assign a DataSource and Bind the results you get from the query say via a DataTable.
Set the DataTextField and DataValueField
Then you can say something like ddl.Items.FindByText("requiredloginid").Selected = true after the Data is bound to the dropdown.

Why are you using
ddlBusinessUnit.DataBind();?
You are binding any data source to the dropdownlist.
Can you specify on which line you are getting error?
Thanks
Ashwani

Related

C# C0246 While Filtering DataGridView with Listbox whose items come from SQL Server

I share with you a piece of code that works except the part where I'm trying to loop in the items of my listbox. That's why I'm here asking you for some help.
Lately, I switched from VBA to C# so I'm still new on this and don't undertsand everything yet.
So, the below code connect to my SQL server DB and fetch data both within my listbox and a DataGridView. I can filter with two textboxes also.
So now I have items within my listbox and my db's view within the DataGridview. I'd like to filter my DataGridview (which is filled by a datatable ) with my Listbox's item. I miss only a silly part I guess. Why Do I get this CS0246 "ListItem could not be found"
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsAppTest
{
public partial class Form1 : Form
{
//Initialize the component and display the items within my listbox CS_Bonds_listBox
public Form1()
{
InitializeComponent();
string connetionString = #"Data Source=my_server;Initial Catalog=my_db;Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(connetionString);
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT DISTINCT RatingProvider FROM Bonds", conn);
adapter.Fill(ds);
this.CS_Bonds_listBox.DataSource = ds.Tables[0];
this.CS_Bonds_listBox.DisplayMember = "RatingProvider";
}
private void Form1_Load(object sender, EventArgs e)
{
}
DataTable dtTEST = new DataTable();
// Next, when clicking on my button Connect, I retrieve my db into a Datatable that is displayed within //the Datagridview1
private void buttonConnect_Click(object sender, EventArgs e)
{
string connetionString = #"Data Source=my_server;Initial Catalog=my_db;Integrated Security=SSPI";
SqlConnection cnn= new SqlConnection(connetionString);
cnn.Open();
MessageBox.Show("Connection Open !");
String sql = "Select * from Bonds";
SqlCommand command = new SqlCommand(sql, cnn);
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = command;
sqlDA.Fill(dtTEST);
dataGridView1.DataSource = dtTEST;
cnn.Close();
}
private void ISIN_Bonds_textBox_TextChanged(object sender, EventArgs e)
{
DataView dv = dtTEST.DefaultView;
dv.RowFilter = "ISIN LIKE '" + ISIN_Bonds_textBox.Text + "%'";
dataGridView1.DataSource = dv;
}
private void Ticker_Bonds_textBox_TextChanged(object sender, EventArgs e)
{
DataView dv1 = dtTEST.DefaultView;
dv1.RowFilter = "Ticker LIKE '" + Ticker_Bonds_textBox.Text + "%'";
dataGridView1.DataSource = dv1;
}
private void CS_Bonds_listBox_SelectedIndexChanged(object sender, EventArgs e)
{
string conString = #"Data Source=my_server;Initial Catalog=my_db;Integrated Security=SSPI";
string query = "SELECT ISIN, Ticker, CrediSight, FROM Bonds";
string condition = string.Empty;
foreach (ListItem item in CS_Bonds_listBox.Items)
{
condition += item.Selected ? string.Format("'{0}',", item.Value) : "";
}
if (!string.IsNullOrEmpty(condition))
{
condition = string.Format(" WHERE Country IN ({0})", condition.Substring(0, condition.Length - 1));
}
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query + condition))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.Connection = con;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
//dataGridView1.DataBind();
}
}
}
}
}
}
}
This line has a problem:
foreach (ListItem item in CS_Bonds_listBox.Items)
A ListItem is a WebForms thing, and your application is a WinForms thing; your listbox doesn't contain a list of ListItem objects so this line of code wouldn't work out anyway, even if the relevant web namespace was imported.
Because you've bound your listbox to a datatable the list it is showing is full of DataRowView objects, so that's what you need to process. A DataRowView has a Row property that gives you the underlying row, which in turn can be accessed by a column name.
Additionally, to make your life easier a listbox has a SelectedItems property so you don't need to check every item for being selected:
foreach (DataRowView drv in CS_Bonds_listBox.SelectedItems)
{
var dr = drv.Row as DataRow;
var rp = dr["RatingProvider"];
condition += $"'{rp}',"
}
Your condition will end up with a trailing comma as a result of this, so trim it off before you build an IN clause with it:
condition = condition.TrimEnd(',');
This technique could be susceptible to SQL Injection hacking if the user manages to change the text showing in the list items.
A better way to handle the problem is via parameterization. You'd do it like this:
var cmd = new SqlCommand("SELECT * FROM table WHERE Country IN(", connStr);
int i = 0;
foreach (DataRowView drv in CS_Bonds_listBox.SelectedItems)
{
var dr = drv.Row as DataRow;
var rp = dr["RatingProvider"];
cmd.CommandText += $"#p{i},";
cmd.Parameters.Add($"#p{i}", SqlDbType.VarChar).Value = rp;
i++;
}
cmd.CommandText = cmd.CommandText.TrimEnd(',') + ")";
using(var da = new SqlDataAdapter(cmd))
{
var dt = new DataTable();
da.Fill(dt);
someGridView.DataSource = dt;
}
This builds an sql that looks like SELECT * FROM table WHERE Country IN(#p0,#p1,#p2.... i.e. we have concatenated parameter placeholders in rather than concatenating values in. At the same time we have filled the parameters collection with the parameter values
It also means that our database can't be hacked via our program, and our app doesn't die in a heap when the user selects a country with a name like Cote d'Ivoire
Some other things to note to tidy your code up:
SqlDataAdapter can take a string SQL and a string connection-string. You don't need to make a SqlCommand for it. You don't need to open and close conenctions for it; it knows how to do all this itself. I only used a SqlCommand because I was building the parameters collection as I went. Ordinarily I'd do using(var da = SqlDataAdapter("SELECT...", "Server=..") because it makes things nice and tidy.
This means e.g. your constructor can be simply:
//put this here once
private string _connStr = #"Data Source=my_server;Initial Catalog=my_db;Integrated Security=SSPI";
public Form1()
{
InitializeComponent();
var dt = new DataTable();
using(var da = new SqlDataAdapter("SELECT DISTINCT RatingProvider FROM Bonds", _connStr))
adapter.Fill(dt);
this.CS_Bonds_listBox.DataSource = dt;
this.CS_Bonds_listBox.DisplayMember = "RatingProvider";
}

Updating a Combobox when when a new row or edit is made to SQLite database

I have a SQLite database. I currently can insert, update and delete records in the database. I have a few combo boxes inside of my program are loaded with the information from my datatable. Currently, for me to get the combo boxes to refresh I must quit the program and start it again to get them to refresh.
I am trying to figure out how I can get the combobox to update once I have entered or edited a record.
The following is my code. I am only showing one combobox that I am trying to update. The comboBoxNameRetrival() is where I am using a query to load my combobox data.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SQLite;
namespace Baby_Tracker
{
public partial class BabyTracker : Form
{
BabyEntryForm babyEntryForm = new BabyEntryForm();
BabyUpdateForm babyUpdateForm = new BabyUpdateForm();
BabyDeleteForm babyDeleteForm = new BabyDeleteForm();
public BabyTracker()
{
InitializeComponent();
comboBoxNameRetrival();
}
/*
* Allows for the BabyEntryForm to be opened for the user to
* add a new entry for a baby.
*/
private void newBaby_btn_Click(object sender, EventArgs e)
{
babyEntryForm.Show();
}
/*
* Allows for the BabyUpdateForm to be opened for the user to
* add a updated entry for a baby.
*/
private void editBaby_btn_Click(object sender, EventArgs e)
{
babyUpdateForm.Show();
}
/*
* Calls the FirstName table from the SQLite database to be displayed inside
* the combob box. This is also set to refresh as a new baby is entered into the
* application.
*/
public void comboBoxNameRetrival()
{
DataTable dt = new DataTable();
string connectionString = "Data Source = BabyDatabase.sqlite; Version=3;";
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteDataAdapter da = new SQLiteDataAdapter("SELECT FirstName FROM BabyList", connection))
{
dt.Clear();
da.Fill(dt);
babySelector_cmbo.DisplayMember = "FirstName";
babySelector_cmbo.DataSource = dt;
connection.Close();
}
}
}
/*
* Used for the selection of the combobox name to be changed throughout the program
* as needed. Also, the image for each baby is changed here where the path is called
* from the database to then load the image for each baby based off of the selection
* from the combobox
*
* Note: The heart of changing data between differenet babies.
*/
private void babySelector_cmbo_SelectedIndexChanged(object sender, EventArgs e)
{
name_lb.Text = babySelector_cmbo.GetItemText(babySelector_cmbo.SelectedItem); //loads the selected name from combobox to theis label
string query = "SELECT BabyImagePath FROM BabyList where FirstName = '" + babySelector_cmbo.GetItemText(babySelector_cmbo.SelectedItem) + "'";
string connectionString = "Data Source = BabyDatabase.sqlite; Version=3;";
SQLiteConnection connection = new SQLiteConnection(connectionString);
SQLiteCommand command = new SQLiteCommand(query, connection);
connection.Open();
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string result = Convert.ToString(reader["BabyImagePath"]);
userImage_box.Image = Image.FromFile(result);
}
}
/*
* Calls the BabyDeleteForm to allow for the user to delete an
* baby entry.
*/
private void deleteBaby_btn_Click(object sender, EventArgs e)
{
babyDeleteForm.Show();
}
}
}
This the class where I am doing all of my updates and adding to the database. The addBabyConnection() method is where I am adding a new user. Here is where I am excepting to call the comboBoxNameRetrival() method in the previous class to update that combobox.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Baby_Tracker
{
class AddUpdateDeleteBaby
{
//String declarations
public string path;
public string targetPath;
/*
* Method is using the data from the BabyEntryForm textboxes to create a new row for
* each new baby entered. The connection and all database requires are set up here.
* BabyList is the table that is being used for the storage of the information.
*/
public void addBabyConnection()
{
string connectionString = "Data Source = BabyDatabase.sqlite; Version=3;";
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
using (SQLiteCommand command = conn.CreateCommand())
{
command.CommandText = "INSERT INTO BabyList (ID, FirstName, MiddleName, LastName, DOB, BirthWeight, BirthLength, BirthHeadCir, BabyImagePath) VALUES (#id, #firstName, #middleName, #lastName, #DOB, #birthWeight, #birthLength, #birthHeadCir, #babyImagePath)";
command.Parameters.AddWithValue("#id", null);
command.Parameters.AddWithValue("#firstName", BabyEntryForm.firstName);
command.Parameters.AddWithValue("#middleName", BabyEntryForm.middleName);
command.Parameters.AddWithValue("#lastName", BabyEntryForm.lastName);
command.Parameters.AddWithValue("#DOB", BabyEntryForm.dob);
command.Parameters.AddWithValue("#birthWeight", BabyEntryForm.weight);
command.Parameters.AddWithValue("#birthLength", BabyEntryForm.length);
command.Parameters.AddWithValue("#birthHeadCir", BabyEntryForm.headCir);
command.Parameters.AddWithValue("#babyImagePath", BabyEntryForm.imagePath);
conn.Open();
command.ExecuteNonQuery();
BabyTracker bt = new BabyTracker();
bt.comboBoxNameRetrival();
}
}
/* Allows for a image to be selected for the baby entry. This is called via
* both new baby entry and also update baby entry. Only JPEG na dPNG images
* are accepted here. The files are then saved to a folder (BabyImages) in
* the application.
*/
public void babyImagePath()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = #"C:\";
openFileDialog.Title = "Selet Baby Profile Image";
openFileDialog.Filter = "Image files (*.jpg, *.jpeg, *.png) | *.jpg; *.jpeg; *.png";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
path = #"C:\Users\Brandon\Documents\Visual Studio 2017\Projects\Baby_Tracker\Baby_Tracker\BabyImages"; //save to file location
targetPath = Path.Combine(path, Path.GetFileName(openFileDialog.FileName));
File.Copy(openFileDialog.FileName, targetPath, true);
}
}
/* Connections to the database to use the information entered from the
* BabyUpdateForm to update the database based upon the fields that
* have entered data.
*/
public void updateBaby()
{
string connectionString = "Data Source = BabyDatabase.sqlite; Version=3;";
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
using (SQLiteCommand command = conn.CreateCommand())
{
command.CommandText = "UPDATE BabyList SET FirstName = #firstName, MiddleName = #middleName, LastName = #lastName, DOB = #DOB, BirthWeight = #birthWeight, BirthLength = #birthLength, BirthHeadCir = #birthHeadCir, BabyImagePath = #babyImagePath WHERE FirstName = '"+BabyUpdateForm.comboName+"'";
command.Parameters.AddWithValue("#firstName", BabyUpdateForm.updateFirstName);
command.Parameters.AddWithValue("#middleName", BabyUpdateForm.updateMiddleName);
command.Parameters.AddWithValue("#lastName", BabyUpdateForm.updateLastName);
command.Parameters.AddWithValue("#DOB", BabyUpdateForm.updatedob);
command.Parameters.AddWithValue("#birthWeight", BabyUpdateForm.updateWeight);
command.Parameters.AddWithValue("#birthLength", BabyUpdateForm.updateLength);
command.Parameters.AddWithValue("#birthHeadCir", BabyUpdateForm.updateHeadCir);
command.Parameters.AddWithValue("#babyImagePath", BabyUpdateForm.updateImagePath);
conn.Open();
command.ExecuteNonQuery();
}
}
/* Connects to the database to allow for the user to delete a baby
* entry that they have previously made. Once a baby is deleted
* from the database, all data is lost on the baby and must
* be reentered as a new baby.
*/
public void deletebaby()
{
string connectionString = "Data Source = BabyDatabase.sqlite; Version=3;";
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
using (SQLiteCommand command = conn.CreateCommand())
{
command.CommandText = "DELETE FROM BabyList WHERE FirstName = '" + BabyDeleteForm.comboName + "'";
conn.Open();
command.ExecuteNonQuery();
}
}
}
}

Run all code within a page consecutively in C# (Using Visual Studio)

I have values from controls txtUser and txtAppNum on a page webform1.aspx. I am bringing those values to a page, Login.aspx. The code from Login.aspx is below. In the login.aspx page, I want to take the values from the controls txtUserand txtAppNum in webform1.aspx page, I want to check the values against a database, if the values are in the database, I want the page to redirect back to webform1.aspx.
My questions is, when I run the code, only Page_Load but not CheckRecord. Basically when I run the page, I can see the values carried over from the webform1.aspx page to login.aspx, but then that's it, nothing else happens.
What am I doing wrong? Any thoughts, I would greatly appreciate it, I have been stuck on this for a few days. Thanks!
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; //to communicate with the Server database
using System.Configuration;
using System.Data; //to use DataSet or DataTable
using System.Text; //for StringBuilder
namespace BLAA_3
{
public partial class login : System.Web.UI.Page
{
public void Page_Load(object sender, EventArgs e)
{
Page PreviousPage = Page.PreviousPage;
if (PreviousPage != null)
{
lblUserLogin.Text = ((TextBox)PreviousPage.FindControl("txtUser")).Text;
lblAppLogin.Text = ((TextBox)PreviousPage.FindControl("txtAppNum")).Text;
}
{
string _connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
}
}
public void CheckRecord(object sender, EventArgs e)
{
//get the connection
using (SqlConnection conn = new SqlConnection(#"Data Source=ServerInfo"))
{
//write the sql statement to execute
string sql = "select username FROM BLAA_users WHERE username = #username";
//instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
//attatch the parameter to pass, if no parameter is in the sql no need to attatch
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#username", SqlDbType.VarChar, 50);
prms[0].Value = lblUserLogin.Text.Trim();
cmd.Parameters.AddRange(prms);
conn.Open();
object obj = cmd.ExecuteScalar();
conn.Close();
if (obj != null)
{
Response.Redirect("~/WebForm1.aspx");
}
else
Response.Redirect("http://www.google.com");
}
}
}
}
}
Is CheckRecord an event handler? If not, you don't need the sender and eventArgs in your signature for CheckRecord it can be public void CheckRecord().
It's not being called because your load event isn't calling it. So, inside your Page_Load function.
public void Page_Load(object sender, EventArgs e)
{
Page PreviousPage = Page.PreviousPage;
if (PreviousPage != null)
{
lblUserLogin.Text = ((TextBox)PreviousPage.FindControl("txtUser")).Text;
lblAppLogin.Text = ((TextBox)PreviousPage.FindControl("txtAppNum")).Text;
}
{
string _connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
}
CheckRecord();
}
public void CheckRecord()
{
//get the connection
using (SqlConnection conn = new SqlConnection(#"Data Source=ServerInfo"))
{
//write the sql statement to execute
string sql = "select username FROM BLAA_users WHERE username = #username";
//instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
//attatch the parameter to pass, if no parameter is in the sql no need to attatch
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#username", SqlDbType.VarChar, 50);
prms[0].Value = lblUserLogin.Text.Trim();
cmd.Parameters.AddRange(prms);
conn.Open();
object obj = cmd.ExecuteScalar();
conn.Close();
if (obj != null)
{
Response.Redirect("~/WebForm1.aspx");
}
else
Response.Redirect("http://www.google.com");
}
}
}

How do I write a database driven dropdown selection to a label?

Another ASP.NET C# noobie question...
The following codebehind populates a dropdown list from a database. There are three columns in the table (ID, ItemType & BinType). I need to be able to return the correct BinType for the row selected by the user:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
// Global variable for SqlConnection
OleDbConnection con = new OleDbConnection();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// specifying sqlconnection string
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_GRPAS_dev"].ConnectionString;
{
// Select rows from database where the ItemType field isn't empty. Sort them alphabetically by ItemType
using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM NF_WhatWasteWhere WHERE ItemType <>'' Order By ItemType"))
{
//Open the connection and populate the dropdown list with ID and Itemtype
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
ItemType1.DataSource = cmd.ExecuteReader();
ItemType1.DataTextField = "ItemType";
ItemType1.DataValueField = "ID";
ItemType1.DataBind();
con.Close();
}
}
// Add a non selectable "Select Item" row at the top of the dropdown list
ItemType1.Items.Insert(0, new ListItem("--Select Item--", "0"));
}
}
protected void ItemType1_SelectedIndexChanged(object sender, EventArgs e)
{
//
// *** Stuff needs to go here in order to continue with the following conditional statement ***
//
if (ItemType1.SelectedValue == "Green")
{
BinResultTest.Text = "<div class='greenBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should be disposed of in a <strong>green bin</strong>.</p></div>";
}
else if (ItemType1.SelectedValue == "Black")
{
BinResultTest.Text = "<div class='blackBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should be disposed of in a <strong>black bin</strong>.</p></div>";
}
else
{
BinResultTest.Text = "<div class='noBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should <strong>NOT</strong> be disposed of in a green or black bin.</p></div>";
}
}
}
What do I need to do to get the conditional statement to work? I presume I need to run another database query - something like the following:
SELECT BinType FROM NF_WhatWasteWhere WHERE ID=" + ItemType1.DataValueField
However, I'm not sure how to code this to establish the connection and return the result.
Any help appreciated.
Thanks.
Edit***
Okay then in protected void ItemType1_SelectedIndexChanged(object sender, EventArgs e)
You can do something similar to what you did with your first query but use an OdbcDataReader
string binValue;
int idHolder = ItemType1.SelectedValue;
con.ConnectionString =System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_GRPAS_dev"].ConnectionString;
{
using (OleDbCommand cmd = new OleDbCommand("SELECT BinType FROM NF_WhatWasteWhere WHERE ID = #Id;"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Id",idHolder);
cmd.Connection = con;
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
if(!DBNull.Value.Equals(reader["BinType"]))
{
binValue = Convert.ToString(reader["BinType"]);
}
}
con.Close();
//Then all your conditionals based off of binValue....
Something like this but maybe a bit more well writen.

C#: help return dataset and assign values to controls

I'm not really used to C# sharp but have used VB.NET before.
I'm needing to set the value of text fields, dropdowns etc from data from a query. To enter the data I have been using a class Computer with the method saveComputer() that takes values from user controls. Now I want an edit page that uses the id from url & uses getComputer(id) from Computer class and returns the values to be set to the user controls. I'm unsure about using this method to set the control values.
Edit.aspx.cs
protected void btnSave_Click(object sender, EventArgs e)
{
int id = 3; //will be replaced to GET value
Computer comp = new Computer();
//comp.updateComputer(ref id);
}
My Computer class
public getComputer(ref int id)
{
DataSet data = new DataSet();
using (SqlConnection conn = new SqlConnection(
"Server=JURA;Database=ReadyForSeven;User id=;Password="))
{
String sql = "SELECT * FROM computers WHERE id=#id";
//replace contatenation of variable with parameter name
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sql.ToString();
cmd.CommandType = CommandType.Text;
//Define SqlParameter object and assign value to the parameter
cmd.Parameters.Add("#id", SqlDbType.Int);
cmd.Parameters["#id"].Value = id;
try
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(data);
// return data here
}
}
catch (SqlException ex)
{
//send user to error page and log message
}
}
}
So what I'm wanting to achieve is using the getcomputer method of Computer to set the values of the controls on Edit.aspx
Can anyone help me out?
You'll need to modify your getComputer method to return a DataSet like:
public DataSet getComputer(int id) {
Once that's done we can call it and populate the form controls on the page load with something like:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
int id = 3; // get from querystring
DataSet ds = getComputer(id);
DataRow dr = ds.Tables[0].Rows[0]; // get the first row returned
// populate form controls
txtFirstName.Text = dr["FirstName"].ToString();
ddlState.SelectedValue = dr["State"].ToString();
}
}
Below is an updated version of getComputer that will always return a value and is a little tighter:
public DataSet getComputer(int id) // you don't need to pass int by ref unless you're planning on changing it inside this method
{
DataSet data = new DataSet();
using (SqlConnection conn = new SqlConnection("Server=JURA;Database=ReadyForSeven;User id=;Password=")) {
using (SqlCommand cmd = new SqlCommand("SELECT * FROM computers WHERE id = #id", conn)) {
cmd.Parameters.AddWithValue("id", id);
using (SqlDataAdapter da = new SqlDataAdapter(cmd)) {
da.Fill(data);
return data;
}
}
}
}
I had to remove the try/catch blog to ensure the method always returned a value. If you absolutely need the try/catch block you'll need to return an empty DataSet at the end of the method to get to compile correctly.

Categories

Resources