Here is basically what i want to do:
i have a web form in asp.net that has a first name and last name and a submit button,
now on submit button click, i would like to display an auto generated voucher code!
how should i go abut it?
this is what i have in my .cs file:
namespace WebApplication1
{
public partial class DetailsForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}``
[WebMethod]
public static string InsertMethod(string firstname, string lastname)
{
SqlConnection con = new SqlConnection(#"Data Source=KIMBERLY\SQLSERVER02;Initial Catalog=Chalegh;User ID=***;Password=***");
SqlCommand cmd = new SqlCommand("insert into TestTable values('"+ firstname +"','" + lastname +"')", con);
con.Open();
cmd.ExecuteNonQuery();
return "True";
}
public static string GenerateVoucher(int length)
{
char[] CharArr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
string randomString = string.Empty;
Random objRandom = new Random();
return randomString;
}
}
}
You need to do several things:
I will create a quick list, (I am assuming that you're using Visual Studio)
1) Create a button to submit button your changes (Drag a button onto the webpage)
2) Create an event handler for your button (Double click on your button)
3) Write the code for your handler
Create an entry in the database
Generate a voucher number
Display it back to the screen
You're pretty close for your database portion, like the comments suggest you want to use parameters instead.
using (var con =new SqlConnection(yourConnectionString))
{
SqlCommand cmd = new SqlCommand("insert into TestTable values('#firstName', '#lastName')", con);
SqlParameter paramFirstName= new SqlParameter();
paramFirstName.ParameterName = "#firstName";
paramFirstName.Value = firstName;
SqlParameter paramLastName= new SqlParameter();
paramLastName.ParameterName = "#lastName";
paramLastName.Value = lastName;
cmd.Parameters.Add(paramFirstName);
cmd.Parameters.Add(paramLastName);
con.Open();
cmd.ExecuteNonQuery();
}
For the generate the voucher number, I like Sudhakar Tillapudi's answer
String randomString = Guid.NewGuid().ToString("N").Substring(0, 6);
Then you need to display it to the screen.
Create a label on your webform (EG: lblVoucherNumber)
Assign the text value to the label
lblVoucherNumber.Text = randomString;
Please note that currently you aren't saving the voucher number. You'll likely want to save that voucher number somewhere (like in your TestTable, please rename this when you put it into production)
you can use GUID.NewGuid() to get the unique ID values.
Try This:
String randomString = Guid.NewGuid().ToString("N");
Suggestion 1: your INSERT INTO statement is open to sql injection attacks so i would suggest you to use Parameterised Queries to avoid them.
Suggestion 2: you need to identify the execution status of the ExecuteNonQuery() method by checking its return value. ExecuteNonQuery() returns total number of rows updated in the database.
Try This:
using(SqlConnection con = new SqlConnection(#"Data Source=KIMBERLY\SQLSERVER02;Initial Catalog=Chalegh;User ID=***;Password=***"))
{
using(SqlCommand cmd = new SqlCommand("insert into TestTable values(#firstname,#lastname)", con))
{
con.Open();
int status = cmd.ExecuteNonQuery();
if(status>0)
return "True";
return "False";
}
}
Related
I am new to C# and am trying to learn how I would be able to change the contents of one drop down list upon the change of another? My current attempt as shown below was unsuccessful, so any advice or help would be appreciated.
protected void drpDwnSchool_TextChanged(object sender, EventArgs e)
{
drpDwnTeacher.Items.Clear();
string selectedSchool = drpDwnSchool.SelectedValue.ToString();
String sqlQueryTeacher = "SELECT * FROM Teacher WHERE SchoolName = '" + selectedSchool + "'";
SqlConnection sqlConnect = new SqlConnection(WebConfigurationManager.ConnectionStrings["Lab1"].ToString());
SqlCommand sqlCommand1 = new SqlCommand();
sqlCommand1.Connection = sqlConnect;
sqlCommand1.CommandType = CommandType.Text;
sqlCommand1.CommandText = sqlQueryTeacher;
sqlConnect.Open();
SqlDataReader queryResultsTeacher = sqlCommand1.ExecuteReader();
while (queryResultsTeacher.Read())
{
string LastName = queryResultsTeacher["LastName"].ToString();
drpDwnTeacher.Items.Add(queryResultsTeacher["LastName"].ToString());
}
sqlConnect.Close();
}
Is it not populating the second list? if so try the "SelectedIndexChanged" event instead of text changed.
Ok, a few issues.
So, on page load, we assume you load up the first drop down.
if (IsPostBack == false)
{
// first time page load schools
LoadSchools();
}
And our code to load the combo box:
public void LoadSchools()
{
string strSQL = "SELECT SchoolName FROM tblSchools ORDER BY SchoolName";
this.DropDownSchools.DataSource = Myrst(strSQL);
this.DropDownSchools.DataBind();
}
So, on the page load, the above fills out the dropdown (combo) with the list of Schools.
Now, when you select a School?
Well, first, you need to set auto-past back for the school combo box.
Now, when a School is selected, you can now display teachers.
I would use the selected index changed, not the text change like you have.
So, that code would look like:
protected void DropDownSchools_SelectedIndexChanged(object sender, EventArgs e)
{
string strSQL;
strSQL = "SELECT Teacher from Teachers WHERE School = '" +
DropDownSchools.SelectedValue + "' ORDER BY Teacher";
DropDownTeachers.DataSource = MyRst(strSQL);
DropDownTeachers.databind();
}
And since for every sql query you have to write for the next 10 years, and create the cmd object, the connect object and the datatable object? Well, lets save some fingers, and you can use a public routine placed in your app_code or where ever you are placing your global wide code. That routine would look like:
public DataTable Myrst(string strSQL, string strCon = "")
{
// this also allows one to pass custom connection string
// - if not passed, then default
if (strCon == "") {
strCon =
ConfigurationManager.ConnectionStrings("WebEasy.My.MySettings.Test3").ConnectionString;
}
SqlConnection mycon = new SqlConnection(strCon);
SqlDataAdapter oReader = new SqlDataAdapter();
DataTable rstData = new DataTable();
oReader.SelectCommand = new SqlCommand(strSQL, mycon);
try
{
oReader.Fill(rstData);
return rstData;
}
catch
{
return null;
}
}
My c# is a bit weak but the above should work.
However, we should be using parameters for this. While dropdowns are not really direct user input, as a future habit, the above code should be using parameters and not string concatenation for the sql.
What works well is to modify the above MyRst to take a sql command object in place of a string, but the above is a good start as to how you can get this type of code to work.
I think the simplest way will be to set the Dropdownlist DataTextField from the HTML source as follows
<asp:DropDownList ID="DropDownList1" DataTextField="YourFieldNameHere" runat="server" />
And also make sure that AutoPostBack is set to true on the Dropdownlist you intend to use for populating the second Dropdownlist.
While on codebehind, bind the Dropdownlist to database as below
protected void drpDwnSchool_TextChanged(object sender, EventArgs e)
{
string selectedSchool = drpDwnSchool.SelectedValue.ToString();
String sqlQueryTeacher = "SELECT * FROM Teacher WHERE SchoolName = '" + selectedSchool + "'";
SqlConnection sqlConnect = new SqlConnection(WebConfigurationManager.ConnectionStrings["Lab1"].ToString());
SqlCommand sqlCommand1 = new SqlCommand();
sqlCommand1.Connection = sqlConnect;
sqlCommand1.CommandType = CommandType.Text;
sqlCommand1.CommandText = sqlQueryTeacher;
sqlConnect.Open();
SqlDataReader queryResultsTeacher = sqlCommand1.ExecuteReader();
if(queryResultsTeacher.HasRows){
DropDownList1.DataSource = queryResultsTeacher;
DropDownList1.DataBind();
}
sqlConnect.Close();
}
I am creating a database application and I'm having difficulty implementing a query. I have a query which populates a combobox with customer's bank accounts this is the code for the query:
private void ShowAccounts()
{
string sql = "SELECT account.custid, product.name FROM account INNER JOIN product ON account.prodid = product.prodid WHERE account.custid = #AccountID";
using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
{
OleDbCommand command = new OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#AccountID", customerData.CustomerID);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
comboAccounts.Items.Add(reader["name"].ToString());
}
}
}
This works the way I need it to but based on the account selection I need to display the account balance and I'm wondering how to go about writing that query. Any help would be appreciated.
Thank you
I guess this is what you are trying to do? I am guessing on your column and table names so you will need to modify the sql statement if I got it wrong.
private string Get_Balance(string AccountNumber)
{
string sql = "SELECT balance FROM account WHERE custid = #AccountID";
string balance = "";
using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
{
OleDbCommand command = new OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#AccountID", AccountNumber);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
balance = reader["balance"].ToString();
}
}
}
return (balance);
}
Use the SelectedIndexChanged event of your combo box to call the above code. You will need to add the event handler to the combo box (just double click it on the form and VS will do it for you).
private void comboAccounts_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboAccounts.Text != "")
{
balanceLabel.text = Get_Balance(comboAccounts.text); //Or whatever you named the label you want your balance to to into.
}
}
After you populate your combo box with your code, whenever the combo box is dropped down and changed it will pass the text of whatever is in the combo box to Get_Balance which will return a string that will be placed in the label.
I have a textbox and a button in a windows form application.
I want to check if the primary key (persId) exists in my sql database/dataset (made with Visual studio) when I enter a number in the textbox and press the button. I dont know how to compare the text with persId from the database.
If the persId exists I want to fill two textboxes in a new form and show the persId and persName.
I am new to programming in C# so I have probably missed something. I looked at how to check if value exists in database from textbox c# but could not find an answer.
Thanks in advance!
public void searchPersId(string persId)
{
SqlConnection conn = new SqlConnection();
SqlCommand myCommand = new SqlCommand("SELECT persId FROM Customers WHERE persId = #persId", conn);
myCommand.Parameters.AddWithValue("#persId", persId);
if (textBox1.Text = myCommand ) //I dont know how to compare the values of textbox with myCommand..
{
//Show values (persId and persName) in two textBoxes in a new form.
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
First, use the using-statement for everything implementing IDisposable like the connection to dispose unmanaged resources and to close the connection, even in case of an error.
Then you have to open the connection and to use ExecuteReader to get a datareader to check if there's at least one record with that ID, you can use reader.HasRows. You also have to select the persName if you want it as mentioned.
using(var conn = new SqlConnection())
using(var myCommand = new SqlCommand("SELECT persId, persName FROM Customers WHERE persId = #persId", conn))
{
myCommand.Parameters.AddWithValue("#persId", persId);
conn.Open();
using(var rd = myCommand.ExecuteReader())
{
bool personExists = rd.HasRows;
if(personExists)
{
// advance the reader to the first record, presuming there is only one, otherwise use a loop while(rd.Read)
rd.Read();
string persName = rd.GetString(1); // second field
// ...
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
}
You can also use ExecuteScalar
public void searchPersId(string persId)
{
SqlConnection conn = new SqlConnection();
SqlCommand myCommand = new SqlCommand("SELECT persName FROM Customers WHERE persId = #persId", conn);
myCommand.Parameters.AddWithValue("#persId", persId);
object personName = myCommand.ExecuteScalar();
if(!string.IsNullOrEmpty(personName.ToString()))
//if (textBox1.Text = myCommand) //I dont know how to compare the values of textbox with myCommand..
{
//Show values (persId and persName) in two textBoxes in a new form.
textBox2.Text = personName.ToString();
}
else
{
MessageBox.Show("The ID does not exist.");
}
}
First you have to Execute the command.
SqlDataReader dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
// ... if it has rows then you know it match
}
else
{
// ... data doesn't exists
}
Then you can compare the result.
I'm creating a windows form and currently in the process of creating the "create member" form.
Now i wish to show to the user inputting data what the new members ID will be. So i thought of trying to show the new row ID within a text box. So if we take the example below, when the form loads, the new member ID should be shown in the textbox
I've tried to attempt it below but having difficulty getting the result from the sqlCommand. Or maybe im going the wrong way around doing it ha
Can anyone see how i can apply the id upon load?
private void frmAddMember_Load(object sender, EventArgs e)
{
using (var connection = new SqlConnection(Properties.Settings.Default.BioEngineeringDB))
{
connection.Open();
using (var cmd = new SqlCommand("SELECT * FROM Users WHERE UserID=(SELECT MAX(UserID) FROM Users", connection))
{
//cmd.Parameters.Add("#MYVALUE", SqlDbType.VarChar).Value = comboBox1.Text;
SqlDataReader re = cmd.ExecuteReader();
if (re.Read())
{
txtMemberId.Text = // result from the SQLCommand but i dont know how to get it
You can access current row cells by indexing DataReader with columns names, like this txtMemberId.Text = thisReader["UserID"]; //here you should do increment. But honestly, generating Id in select max(id) + 1 manner is odd, GUIDs nad Autoinc integer is more commonly used in our days.
Your MAX+1 should looks like:
private void frmAddMember_Load(object sender, EventArgs e)
{
using (var connection = new SqlConnection(Properties.Settings.Default.BioEngineeringDB))
{
connection.Open();
using (var cmd = new SqlCommand("SELECT (COALESCE(MAX(UserID), 0) + 1) as UserID FROM Users", connection))
{
SqlDataReader re = cmd.ExecuteReader();
if (re.Read())
{
txtMemberId.Text = re["UserID"].ToString();
remove your autoinc id column and add a guid id col instead. then you can generate the Id on the client with Guid.NewGuid().ToString()
Assuming your ID column is being generated by the database (auto increment, etc...) just get the ID when you create the record.
var cmd = new SqlCommand("INSERT INTO User(FirstName) VALUES('bob')");
var id = (int) cmd.ExecuteScalar();
txtMemberId.Text = id.ToString();
I have a database that contains a table named "User(login,password,firstname,lastname)" . And I need to make login page . I've watched some tutorials , but it didn't help . I need to check if login and password exist in the database . and then redirect(if correct) to other page . This is what I already did:
OleDbConnection con = new OleDbConnection();
public bool check()
{
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Volodia\Documents\WebSiteDatabase.accdb";
con.Open();
string commandstring = "SELECT login,password FROM User";
//objadapter = new SqlDataAdapter(CommandString, sqlconn.ConnectionString);
OleDbDataAdapter objadapter = new OleDbDataAdapter(commandstring, con.ConnectionString);
DataSet dataset = new DataSet();
objadapter.Fill(dataset, "User");// it shows "Syntax error in FROM clause." here
DataTable datatable = dataset.Tables[0];
for (int i = 0; i < datatable.Rows.Count; i++)
{
string unam = datatable.Rows[i]["login"].ToString();
string upwd = datatable.Rows[i]["password"].ToString();
if ((unam == TextBox1.Text)&&(upwd==TextBox2.Text))
{
return true;
}
}
return false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (check() == true)
{
Response.Redirect("WebForm2.aspx");
}
}
The word PASSWORD is a reserved keyword for MS-Access Jet SQL. If you want to use it you need to enclose it in square brackets, the same for USER
string commandstring = "SELECT login, [password] FROM [User]";
This will resolve the immediate problem of the Syntax Error but let me add some other code to show a different approach
public bool check()
{
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Volodia\Documents\WebSiteDatabase.accdb";
using(OleDbConnection con = new OleDbConnection(conString)
{
con.Open();
string commandstring = "SELECT count(*) as cntUser FROM [User] " +
"WHERE login = ? AND [password] = ?";
using(OleDbCommand cmd = new OleDbCommand(commandstring, con))
{
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.Parameters.AddWithValue("#p2", TextBox2.Text);
int result = (int)cmd.ExecuteScalar();
if(result > 0)
return true;
}
}
return false;
}
First, do not use a global connection object but create and use the
connection only when needed.
Second, encapsulate the disposable objects like the connection and
the command with the using statement that will ensure a correct close
and dispose,
Third, pass the login and the password as conditions for the where
clause (more on this later)
Fourth, use the parametrized query to avoid syntax errors and sql
injection
Usually is not a good practice to store a password in clear text inside the database. You need to store only the hash of the password and recalculate this hash every time you need to check the user authenticity