i am working on C# .net platform
i wanted to connect my combox to my text box
this is code done by me but it is give me error
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
panel1.Visible = true;
string sql;
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "Data Source=CJ\SQLEXPRESS;Initial Catalog=elligiblity;Persist Security Info=True;User ID=sa;Password=123";
cn.Open();
sql = "SELECT inst_name FROM institude WHERE(inst_id="+comboBox2.SelectedItem+")";
SqlCommand cmd = new SqlCommand(sql,cn);
SqlDataReader myReader = cmd.ExecuteReader();
while(myReader.Read())
{
textBox2.Text = myReader["inst_name"].ToString();
}
myReader.Close();
cn.Close();
The multi-part identifier "System.Data.DataRowView" could not be bound.
on this line of the code
SqlDataReader myReader = cmd.ExecuteReader();
As well as that problem there are a few issues with your code that you might want to bear in mind.
Firstly, if there is an error between opening and closing the connection (as indeed there was) then you're probably going to leave connections open. Eventually this will choke your site. Use
using (SqlConnection cn = new SqlConnection())
{
}
when you're out of the scope of the using statement the connection will be closed and disposed of.
Also, you probably want to parameterize your query (for reasons both of security and efficiency), so that it is
sql = "SELECT inst_name FROM institude WHERE(inst_id=#inst_id)";
Then add that parameter to your command object and set its value to your combo box selected item value.
You want
comboBox2.SelectedValue
or
comboxBox2.SelectedItem.ToString()
then but I'd look at using parameters instead as that's not a very good way of creating a SQL string.
Also, do you realise that if you return more than one result your textbox2 will only show the last result as its text will get over-ridden with each result as its read?
First of all check the binding of dropdown. If you are binding datasource with ID and Text something like this combobox2.DisplayMember ="Name"; combobox2.ValueMember ="ID". After that you have to check for the parameter to be used in your query if its text then try combobox2.text else if you are selecting on the basis of id use int.parse(combobox2.selectedvalue) or simply combobox2.selectedvalue if your id is alphanumeric.
Related
I want to show result of a query in a MessageBox in C#, but the code below doesn't work.
private void button26_Click(object sender, EventArgs e)
{
string constring =
#"Data Source=blahblahblah;user id=blah;password=blah;database=blah;";
SqlConnection con = new SqlConnection(constring);
SqlCommand check = new SqlCommand("select blah from blah where blah=#blah");
check.Parameters.AddWithValue("#blah", textBox1.Text);
con.Open();
string gholi = check.ExecuteScalar().ToString();
con.Close();
MessageBox.Show(gholi);
}
I think best way to see result of code, run application and set breakpoint in first line code.
if you want the next step press F10.
you can see the relevant details with debug code.
You should sql reader to read data from data base or you can use dataset to retrive data from database and then trying display in message box.
I've ordered SQL Server from Somee. I want to use this SQL Server for my windows form. Somehow, i'm not sure, but whenever i execute the login query what i've found, it will have an unhandled exeption.
private void log_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "workstation id=wbhandler.mssql.somee.com;packet size=4096;user id=acc;pwd=pw;data source=wbhandler.mssql.somee.com;persist security info=False;initial catalog=wbhandler";
con.Open();
string felh = username.Text;
string jelsz = password.Text;
string query = "SELECT * FROM accounts WHERE account=#felhasznalo AND password=#jelszó";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#felhasznalo", felh));
cmd.Parameters.Add(new SqlParameter("#jelszó", jelsz));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true )
{
MessageBox.Show("Succes");
}
else
{
MessageBox.Show("Failed");
}
}
I thought that the adress is wrong, but then i found on the website the connection string, and now i don't really know.
I'm thinking what's the problem is.
I have 3 schemes in the sql:
dbo, acc, guest.
I first created a table in dbo, then in acc. Now in both of it. But it doesn't execute the SqlDataReader dr = cmd.ExecuteReader();, sadly. Like i said, it has unhandled exeption. Any solution? Any ideas?
(the acc scheme is an example what i created in somee, so it doesn't exist, it's fake)
I also tried this way:
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
MessageBox.Show("Sikeres Login!");
}
else
{
MessageBox.Show("Sikertelen Login");
}
}
The problem is always the ExecuteReader()
Try the SqlParameterCollection.AddWithValue Method instead:
cmd.Parameters.AddWithValue("#felhasznalo", felh);
cmd.Parameters.AddWithValue("#jelszó", jelsz);
I will also recommend that you use using statements on your SQL objects to ensure that the unmanaged resources they consume are freed when they are no longer needed. You can read more on the using statement from here.
Another thing that I can suggest is adding Charset=utf8; to your connection string.
I am trying to get a drop down list to display data from MYSQL database, database table name is Pet and I am trying to get the information from Specie.
Now the code looks good to me but it is not running so its always best to get another pair of eyes to look over it.
Thanks,
All help is appreciated.
connection string
MySqlConnection cs = new MySqlConnection(#"Data Source = 000.000.00.000;username=benoatsc_admin;password=****; Initial Catalog = dbname; Integrated Security = true");
drop down code
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
MySqlCommand cd = new MySqlCommand("SELECT * FROM Pet", cs);
cs.Open();
MySqlDataReader ddl = cd.ExecuteReader();
DdPetList.DataSource = ddl;
DdPetList.DataValueField = "Specie";
DdPetList.DataTextField = "Specie";
DdPetList.DataBind();
cs.Close();
cs.Dispose();
}
There are a few problems here:
You should likely move this code to the Page_Load method. I would assume that you want this DropDownList populated when the page loads for the user. Otherwise, the DropDownList is never populated with the data from your MySQL Database, hence you will not be able to trigger the SelectedIndexChanged event when there is no index to possibly change.
MySQL Connector/Net makes use of unmanaged resources. These should be disposed of when they are finished being used. The .NET Framework offers an elegant way to ensure that objects utilizing unmanaged resources are disposed of in the form of using statements. It is best practice to use them.
When MySqlConnection, MySqlDataReader, etc. should not only be disposed of when they are done being used, but they should also be closed. Thankfully, when dispose() is called on these objects their close() methods are called as well.
So piecing this all together yields this piece of code:
protected void Page_Load(object sender, EventArgs e)
{
using (var conn = new MySqlConnection(/* Your connection string here */))
{
conn.Open();
using (var cmd = new MySqlCommand("SELECT * FROM Pet", conn))
{
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
DropDownList1.DataSource = reader;
DropDownList1.DataValueField = "Specie";
DropDownList1.DataTextField = "Specie";
DropDownList1.DataBind();
}
}
}
}
}
I hope this all helps. If you need any clarifications, I will gladly provide it.
This would be a comment but i don't have the reputation,
what error message are you receiving ?
your connection string has got both trusted connection set to true and you are providing credentials,
remove one of them.
I'm trying to upgrade the db from users' input, but it doesn't work...
I'm using this:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand();
SqlCommand ncmd = new SqlCommand("Update Utenti Set Nome = #vnome where [Indirizzo E-Mail]=#vem", con);
ncmd.Parameters.AddWithValue("#vem", Session["[Indirizzo E-Mail]"].ToString());
ncmd.Parameters.AddWithValue("#vnome", TextBox2.Text);
ncmd.Connection = con;
con.Open();
ncmd.ExecuteNonQuery();
con.Close();
Label2.Text = "Dati aggiornati con successo!";
Response.Redirect("~/ModificaDati.aspx");
}
When I click on the button it show me the Label2 text, but in the database the "Nome" is not changed, why?
Thanks before for the answers ^^
I would change your method as below
if (Session["[Indirizzo E-Mail]"] != null &&
!string.IsNullOrEmpty(Session["[Indirizzo E-Mail]"].ToString()) &&
!string.IsNullOrEmpty(TextBox2.Text))
{
string vem = Session["[Indirizzo E-Mail]"].ToString();
using (var con = new SqlConnection(strcon))
using (var ncmd = new SqlCommand("Update Utenti Set Nome = #vnome where [Indirizzo E-Mail]=#vem", con))
{
con.Open();
ncmd.Parameters.AddWithValue("#vem", vem);
ncmd.Parameters.AddWithValue("#vnome", TextBox2.Text);
int rows = ncmd.ExecuteNonQuery();
Label2.Text = rows + " Dati aggiornati con successo!";
}
}
Response.Redirect("~/ModificaDati.aspx");
Added input validation, session values can be null, better to check before you update database
when you create SqlCommand you can give the connection, no need to set it again
make sure your SQL is valid
use using statements for disposable objects like SqlConnection, SqlCommand
Your code looks ok. Just make sure you check if SQL is correct as Damith already suggested.
Another thing I’s recommend is additionally validating your parameters for data type correctness before executing the query.
Using this approach you’ll probably avoid a lot of unnecessary exceptions and also be able to provide more user friendly messages. Of course this only applies if user input is non text type
//Data Type verification
DateTime tmp;
if (!DateTime.TryParse(Label2.Text.Trim(), out tmp))
{
//Show error message that this is not a correct data type
}
Open your connection first
con.Open();
ncmd.Connection = con;
Hope it helps
I am creating a login form. Where if the Login-id and password matches with the values stored in Register table it retrieves all values from Register table and the result stores in the SqlDataReader object .So, now I want to access accountid and type from this table.How can we do it?
To understand what I am trying to say please have a look on the following code-
--------------------Login.aspx.cs---------------------------------------------------------------
protected void Submit_Click(object sender, EventArgs e)
{
string conStr = ConfigurationManager.ConnectionStrings["ROCConStr"].ConnectionString;
SqlConnection scon = new SqlConnection(conStr);
scon.Open();
SqlCommand cmd = new SqlCommand("select* from Register where email= #login_id and pwd=#password", scon);
SqlParameter Para;
Para = cmd.Parameters.Add("#login_id", SqlDbType.Char);
Para.Value = email.Text;
Para = cmd.Parameters.Add("#password", SqlDbType.Char);
Para.Value = pwd.Text;
SqlDataReader reader = cmd.ExecuteReader();
if(reader.HasRows)
{if (reader["account_type"]=="admin") /* error - Please see the bottom for more details.*/
Response.Redirect("http://localhost:1187/roc/WelcomeAdmin.aspx");
else
Response.Redirect("http://localhost:1187/roc/WelcomeUser.aspx");}
else
{ Label1.Text = "UserID or password is incorrect."; }
reader.Close();
scon.Close();
}
==================================================
<br>About the erro:- reader["account_type"]=="admin"
I dont know how to retrieve the value of a single column.So, I just typed to show what I want to do. I tested this code I got the error - "Invalid attempt to read when no data is present."
You need to call reader.Read() to move to the first row.
Alternatively, change your query to select only the column you want, then call ExecuteScalar to return that value directly (or null if there were no rows) without using a DataReader at all.
(you can't do this, since you want more than one column)
You've only checked to see if you 'HasRows'; but you still need to advance the Reader. reader.Read()
That should fix your problem. You might want to also consider incorporating 'using' statements to limit the scope of your objects and modifying your URLs to use relative paths instead of absolute. That way, if you deploy to a new environment or move servers you don't have to remove the hard-coded URL.