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.
Related
i am encountering an error when trying to set up an insert command into my database, it appears to be with the connection string. I am extremely new to all this and am trying to get the correct code in order to upload into my database and assume that the syntax i am using may be wrong and the cause of the error.
Here is the code a little bit clearer:
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;
namespace ComputingProjectwh.TestPages._1._Further_Mechanics
{
public partial class Moments_and_Energy_Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
if (!this.IsValid)
return;
int score = 0;
List<RadioButtonList> list = new List<RadioButtonList>() { RadioButtonList1, RadioButtonList2, RadioButtonList3, RadioButtonList4, RadioButtonList5, RadioButtonList6, RadioButtonList7, RadioButtonList8, RadioButtonList9, RadioButtonList10 };
foreach (var element in list)
{
if (element.SelectedValue == "Correct")
{
score++;
}
}
Response.Write("you scored: " + score);
Button1.Visible = false;
if (score != 0);
{
SqlConnection sqlConnection1 = new SqlConnection (#"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ComputingProjectwh-20170404101246.mdf;InitialCatalog=aspnet-ComputingProjectwh-20170404101246;IntegratedSecurity=True");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT AspNetUserTestScores (Id, MomentAndEnergyTestScore) VALUES (Id, score)";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
}
}
I am really not sure what the problem is and cant seem to find an answer on the internet. Any help would be greatly appreciated.
When connecting to MSSQL, there is no initialcatalog, You are using a wrong connection string.
This is the correct syntax:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Or in your case, for trusted connection:
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
With your data:
SqlConnection sqlConnection1 = new SqlConnection("Server=LocalDb;Database=aspnet-ComputingProjectwh-20170404101246.mdf;Trusted_Connection=True;");
InitialCatalog is two separate words initial catalog.
I've just started learning C# using Visual Studio 2015, and my task is to create a lottery program that saves the generated numbers into a database. I've tried various methods and none of them seem to make any additions to my table. Can anyone help me understand what I need to do take an Integer that has been generated and converted into a string/ textbox and then insert that value into my table.
Heres my current code below, button 2 being the button I am trying to use to save the data from the textboxes with.
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.Configuration;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
//Database details
string connectionString;
SqlConnection connection;
public Form1()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApplication2.Properties.Settings.LottoConnectionString"].ConnectionString;
}
private void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int[] slot = new int[6];
int counter = 0;
for (int i = 0; i < slot.Length; i++)
{
slot[i] = rnd.Next(0, 100);
}
//Converting generated ints to Strings for display
textBox1.Text = (slot[0].ToString());
textBox2.Text = (slot[1].ToString());
textBox3.Text = (slot[2].ToString());
textBox4.Text = (slot[3].ToString());
textBox5.Text = (slot[4].ToString());
textBox6.Text = (slot[5].ToString());
//Incrementing Counter checks matches
if (numericUpDown1.Value == slot[0])
{
counter += 1;
}
if (numericUpDown2.Value == slot[1])
{
counter += 1;
}
if (numericUpDown3.Value == slot[2])
{
counter += 1;
}
if (numericUpDown4.Value == slot[3])
{
counter += 1;
}
if (numericUpDown5.Value == slot[4])
{
counter += 1;
}
if (numericUpDown6.Value == slot[5])
{
counter += 1;
}
//display total matches
textBox7.Text = ("You got" + counter + "/6 matches!");
LottoDataSetTableAdapters.ResultsTableAdapter resultsTableAdapter =
new LottoDataSetTableAdapters.ResultsTableAdapter();
resultsTableAdapter.Insert((slot[0].ToString()), (slot[1].ToString()), (slot[2].ToString()), (slot[3].ToString()), (slot[4].ToString()), (slot[5].ToString()));
}
private void button2_Click(object sender, EventArgs e)
{
// Adding Data to Database
string query = "INSERT INTO Results VALUES (#First)";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#First", textBox1.Text);
command.Parameters.AddWithValue("#Second", textBox2.Text);
command.Parameters.AddWithValue("#Third", textBox3.Text);
command.Parameters.AddWithValue("#Fourth", textBox4.Text);
command.Parameters.AddWithValue("#Fifth", textBox5.Text);
command.Parameters.AddWithValue("#Sixth", textBox6.Text);
}
}
}
}
All help will be greatly appreciated.
Your INSERT statement is missing the other parameters in the VALUES portion. You also need to execute the command and you were missing brackets for the using of the connection.
private void button2_Click(object sender, EventArgs e)
{
// Adding Data to Database
string query = "INSERT INTO Results (First, Second, Third, Fourth, Fifth, Sixth) VALUES (#First, #Second, #Third, #Fourth, #Fifth, #Sixth)";
using (var connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#First", textBox1.Text);
command.Parameters.AddWithValue("#Second", textBox2.Text);
command.Parameters.AddWithValue("#Third", textBox3.Text);
command.Parameters.AddWithValue("#Fourth", textBox4.Text);
command.Parameters.AddWithValue("#Fifth", textBox5.Text);
command.Parameters.AddWithValue("#Sixth", textBox6.Text);
command.ExecuteNonQuery();
}
}
}
It looks like this question as been asked and answered before - have a look here - How to insert data into SQL Server
edit - my first impression was wrong, I can't see where you are executing your query against the db. its been a while since it have written ado code manual without using an orm so forgive me if i am wrong.
The code does connect to the database and actually check the username(number) and then exception runs when it has to get to verifying the password and a null reference is thrown
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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Intellicell_CallCentreConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT COUNT(*) FROM Debtors WHERE MobilePhone='" + txtMobilePhone.Text + "'";
SqlCommand cmd = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string CheckPasswordQuery = "SELECT IDNumber from Debtors WHERE MobilePhone='" + txtPassword.Text + "'";
SqlCommand passCmd = new SqlCommand(CheckPasswordQuery, conn);
string password = passCmd.ExecuteScalar().ToString().Replace(" ","");
conn.Close();
if (password == txtPassword.Text)
{
Session["New"] = txtMobilePhone.Text;
Response.Write("Password is correct!");
Response.Redirect("Home.aspx");
}
else
{
Response.Write("Password is not correct!");
}
}
else
{
Response.Write("Please Provide valid Login details!");
}
}
}
it is on line
string password = passCmd.ExecuteScalar().ToString().Replace(" ","");
that it breaks.
I suggest you if you want write sql adhoc, use string.format
It's clean
string checkuser = string.Format("SELECT COUNT(*) FROM Debtors WHERE MobilePhone={0},txtMobilePhone.Text);
Secondly, you can use using syntax , in order to clean your connection properly
I think, In the second sql you are using txtPassword.Text instead of txtMobilePhone.Text
The question is why are you getting the null execption, see this: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
In summary ExecuteScaler returns a null (not a DBNull) if no rows are found, whence passCmd.ExecuteScalar().ToString().Replace(" ",""); null refences as its null.ToString()
You global logic looks flawed so hard to suggest exactly what to do, but passCmd.ExecuteScalar()?.ToString().Replace(" ","") will suppress the exeception.
I have been trying to figure this out for hours now, I know there is some small error that I have here but I am not able to pinpoint it. Please help me.
So I created a class called "clsDataLayer.cs" and it is in the App_Code asp.net folder.
I then created a form called "frmUserActivity", but now when I post the code in it and call the class it says "The "clsDataLayer" does not exists in current context" Can anyone please help me?
code for clsDataLayer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// Add your comments here
using System.Data.OleDb;
using System.Net;
using System.Data;
namespace ASP_PayRoll.App_Code
{
public class clsDataLayer
{
// This function gets the user activity from the tblUserActivity
public static dsUserActivity GetUserActivity(string Database)
{
// Add your comments here
dsUserActivity DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
// Add your comments here
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
// Add your comments here
sqlDA = new OleDbDataAdapter("select * from tblUserActivity", sqlConn);
// Add your comments here
DS = new dsUserActivity();
// Add your comments here
sqlDA.Fill(DS.tblUserActivity);
// Add your comments here
return DS;
}
// This function saves the user activity
public static void SaveUserActivity(string Database, string FormAccessed)
{
// Add your comments here
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
strSQL = "Insert into tblUserActivity (UserIP, FormAccessed) values ('" +
GetIP4Address() + "', '" + FormAccessed + "')";
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.Close();
}
// This function gets the IP Address
public static string GetIP4Address()
{
string IP4Address = string.Empty;
foreach (IPAddress IPA in
Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != string.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
}
}
Code for frmUserActivity.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ASP_PayRoll
{
public partial class frmUserActivity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Declare the DataSet
dsUserActivity myDataSet = new dsUserActivity();
//Fill the dataset with what is returned from the function
myDataSet = clsDataLayer.GetUserActivity(Server.MapPath("PayrollSystem_DB.mdb"));
//Sets the DataGrip to the DataSource based on the table
grdUserActivity.DataSource = myDataSet.Tables["tblUserActivity"];
//Binds the DataGrid
grdUserActivity.DataBind();
}
}
}
}
Thanks in advance.
Ak
Use ASP_PayRoll.App_Code.clsDataLayer. Your namespace in your data layer class is ASP_PayRoll.App_Code and in your page it's ASP_PayRoll.
Add using ASP_PayRoll.App_Code; to your aspx file.
Since you declared that in a namespace other than the one of your aspx page, you have to use a using statement, or the entire path (ASP_PayRoll.App_Code.clsDataLayer) in order to be able to access that class.
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