How can we link combobox with database table? - c#

I have a combox called comboBox2 and i want to fill this combobox with a column named 'Stud_Name' of my database table called 'Student_Table'
I use the following code:
void Fillcombo()
{
string constring = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\ChaCha\\ChaCha\\chacha.mdf;Integrated Security=False";
string query = "select * from database.Student_Table";
SqlConnection condb = new SqlConnection(constring);
SqlCommand cmddb = new SqlCommand(query, condb);
SqlDataReader myreader;
try
{
condb.Open();
myreader = cmddb.ExecuteReader();
while(myreader.Read())
{
string sName = myreader.GetString("Stud_Name");
comboBox2.Items.Add(sName);
}
}
catch (Exception ex)
{
}
}
But, I am getting an error message like this:
The best overloaded method match for
'System.Data.Common.DbDataReader.GetString(int)' has some invalid
arguments.
How can I remove this error?
I use Visual Studio 2012.

Error message is clearly says;
There is no overload of SqlDataReader.GetString method that takes string as a parameter.
This method takes int as a parameter which is the number of zero-based column that you want to get.
You need to put as an integer value which is Stud_Name column number in your query.
For example; if your Stud_Name is the first column of your query, you can use it like;
string sName = myreader.GetString(0);
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataReader.

Your problem is the parameter you pass to the method called GetString. Uou should pass there the index of the column, you want to read from. Instead of doing this, you pass the name of the column. That's why you get this error message.
For more documentation, please have a look here.

Related

Row Deletion ADO.Net, ASP.Net

I am trying to work with a contact list and want to remove all of the info on a person when I type in their name. I am using a sql table -named Contact- that contains the Name, Email and Address of a contact. I have the following code:
protected void Delete_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnect"].ConnectionString);
con.Open();
string delete = "DELETE FROM Contact WHERE Name =" + NameToDelete.Text;
SqlCommand cmd = new SqlCommand(delete, con);
try
{
cmd.Parameters.AddWithValue("#Name", delete);
cmd.ExecuteNonQuery();
Response.Redirect("ViewContacts.aspx");
}
catch(Exception ex)
{
Response.Write(ex);
}
}
When I use this, it seems to be comparing the column Name to the name I am putting in. So the name Bill is being compared against the column header Name instead of what is in the name.
You need to use single quotes around the values with var(char) types. If you don't use quotes it will think that you are referencing a column name instead of value.
It's valid for all databases, following is from oracle docs:
character literals are enclosed in single quotation marks, which
enable Oracle to distinguish them from schema object names.
https://docs.oracle.com/cd/A87860_01/doc/server.817/a85397/sql_elem.htm
string delete = "DELETE FROM Contact WHERE Name ='" + NameToDelete.Text + "'";
Actually what you are trying to do is using sqlcommand parameter, then you need to use parameter name using #[ParameterName] in sql statement.
string delete = "DELETE FROM Contact WHERE Name = #Name";
Seems that your problem is that you are using the variable delete in two instances. First for create the command that is fine and second as the parameter value, which is wrong. In the parameter value probably you must use the value tthat you want to delete.
You have several serious problems with your code.
Your connection is never closed or disposed. Use Using blocks which will close and dispose of database objects even if there is an error.
You are concatenating a string to get your Sql statement risking Sql injection and damage to your database.
You are adding a parameter to your command when there are no parameters in your Sql statement.
You are using .AddWithValue which takes the parameter name and the parameter value as arguments. You have provided your entire Sql statement as the value of #Name. This should be NameToDelete.Text.
Do not use .AddWithValue. Use .Add(parameter Name, Sql data type).Value = value of parameter. This can speed up queries and avoids type mismatches in the database.
If name is your Primary Key, you are OK, but if not you should delete by the primary key or send all values in the Where clause.
protected void Delete_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnect"].ConnectionString))
{
string delete = "DELETE FROM Contact WHERE Name = #Name;"; //no single quotes to worry about
using (SqlCommand cmd = new SqlCommand(delete, con))
{
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = NameToDelete.Text; //just guessed at the VarChar - check your database for type
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("ViewContacts.aspx");
}
catch (Exception ex)
{
Response.Write(ex.Message); //ex by itself, will get you nothing but the fully qualified name of Exception
}
}
}
}

Fill combobox with SQL Server column values

Could you please assist me, I am trying to fill a combobox with values from a column in a SQL Server table. I have tried various methods, but none of them returned the desired result.
The error is:
Error CS1503 Argument 1: cannot convert from 'string' to 'int'
This is my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
fillCombo();
}
void fillCombo()
{
string con = "Data Source = xxxxx; Initial Catalog = xxxxx; Integrated Security = False; User Id = xxxxx; Password=xxxx;MultipleActiveResultSets=True";
string Query = "select * from LEAVE ;";
SqlConnection conDataBase = new SqlConnection(con);
SqlCommand cmd = new SqlCommand(Query, conDataBase);
SqlDataReader dr;
try
{
conDataBase.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
string lveName = dr.GetString("lve_name");
lveType.Items.Add(lveName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I would do this instead:
Dictionary<int, string> lveNames = new Dictionary<int, string>();
while (dr.Read())
{
string lveName = dr["lve_name"].ToString();
int lveId = int.Parse(dr["lve_id"].ToString());
lveNames.Add(lveId, lveName);
}
lveType.DataSource = new BindingSource(lveNames, null);
lveType.DisplayMember = "lveName";
lveType.ValueMember = "lveId";
Assuming that you have id lve_id.
DisplayMember and ValueMember are used to bind the label and id to the combo box.
Always look at the signatures of the methods you are trying to use:
dr.GetString(int)
You are trying to call
dr.GetString(string)
but there's not overloaded method that accepts a string. See the documentation of GetString().
Instead, GetString requires you to pass the zero based ordinal of the column you are trying to get the string from. Let's say lve_name is the second column in your query (a bit hard to tell, since you are using SELECT * FROM, but that's another topic), you have to use it like this:
string lveName = dr.GetString(1);
Also, check what the documentation has to say:
No conversions are performed; therefore, the data retrieved must already be a string.
This means, if your query returns anything other than a string, the method will most likely throw an InvalidCastException. To prevent that from happening, you have to edit your query, like for example
SELECT lve_id, CAST(lve_name as varchar) FROM LEAVE
Another possible solution would be to access the column like this:
string lveName = dr["lve_name"].ToString()

SqlDataReader - correct syntax, must I hardcode column number?

I have a database named testDB, which contains table Versions, which contains a column [Release Date] with datetime format.
Now, I want to read it in my C# Windows Service:
protected void SqlConnect()
{
SqlCommand comSql;
DateTime relDate;
SqlDataReader myReader = null;
using (SqlConnection myConnection = new SqlConnection(_server +
_username +
_password +
"Trusted_Connection=yes;" +
"database=testDB; " +
"connection timeout=30"))
{
try
{
myConnection.Open();
comSql = new SqlCommand("select [Release Date] from dbo.Version",
myConnection);
myReader = comSql.ExecuteReader();
while (myReader.Read())
{
//Here's my problem, explained below
}
}
catch
{
}
finally
{
if (myReader != null) myReader.Close();
}
}
}
Now, I want to assign the value stored in that column to relDate variable. However
relDate = myReader.GetDateTime();
requires GetDateTime to have column number passed there (if I understand this right). But I already selected column in my comSql. Is this the correct way to deal with this problem, ie. just putting the column number in the code?
EDIT: Ok judging by the answers I might word this question wrong or something.
I know that I must pass the column index to GetDateTime(). I ask if there's a way to do that without hardcoding it like GetDateTime(0).
You can use GetOrdinal method on the data reader to get ordinal of the column from its string name. In that way, you won't have to hardcode the column index.
GetOrdinal is also useful when you're reading data from the data reader in a loop. You can initialize the index variable before the loop starts and then use it in every iteration of the loop.

How to pass table name as parameter in OleDB?

private void button1_Click(object sender, EventArgs e)
{
string tablename = label2.Text;
string name = TextBox1.Text;
DBconnection.savetodb(tablename, name);
}
I call the method below from another form to save the name into a specific table. But it wont save into my table in database.
public static void savetodb(string tablename, string name)
{
OleDbConnection connection = GetConnection();
string query = String.Format("INSERT INTO {0} (Name) VALUES (#Name)", tablename);
OleDbCommand cmd = new OleDbCommand(query, connection);
cmd.Parameters.AddWithValue("#Name", name);
try{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex){
Console.WriteLine("Exception catch", ex);
}
finally{
myConnection.Close();
}
Thanks for help.
You are not passing table name as a parameter, you are passing your #Name value as a parameter. You can't pass a table name as a parameter even if you want. Parameters only for values, not table or column names. You are just formatting your query based table name. As far as I see, your problem using named parameters. OleDb provider does not support named parameters.
From OleDbCommand.Parameters
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the
OleDbParameterCollection must directly correspond to the position of
the question mark placeholder for the parameter in the command text.
Try it as;
string query = String.Format("INSERT INTO {0} (Name) VALUES (?)", tablename);
...
cmd.Parameters.AddWithValue("#name", name);
Also use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection connection = new GetConnection())
using(OleDbCommand cmd = con.CreateCommand())
{
}
And consider to use .Add method instead .AddWithValue. It may cause some problems. Read Can we stop using AddWithValue() already?

C#: Input data from string array into MS Access DB Table

I've searched as much as I can and can't find anything to help me. So what I have is a script that reads/splits and stores data from a .txt file into some arrays. (The one listed here is Vndnbr). What I'm having trouble with is how to go about inputting each entry in the array as an entry under a column in a MS Access table? This is what I have so far:
public void AddToDatabase()
{
OleDbCommand command;
OleDbConnection connection =
new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=filepath");
foreach (string x in Vndnbr)
{
cmdstringVND[k] = "insert into Table1 (Vndnbr) Values (x)";
k++;
command = OleDbCommand(cmdstringVND[k],connection);
}
command.Parameters.AddWithValue("?", ReadFromFile("filepath"));
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
I'm not familiar with the Access library or what should be inserted in the first parameter of AddwithValue as I just copy pasted these lines after doing some research.
If someone could help me with how to add all the data from an array into a table it would be greatly appreciated, thanks.
There are many errors in your code
In your loop you don't use a parameter to store the value to be
inserted
You never creare the command. (Use new)
You try to execute only the last command because the ExecuteNonQuery is outside the loop
public void AddToDatabase()
{
string cmdText = "insert into Table1 (Vndnbr) Values (?)";
using(OleDbConnection connection = new OleDbConnection(.....))
using(OleDbCommand command = new OleDbCommand(cmdText, connection))
{
connection.Open();
command.Parameters.AddWithValue("#p1", "");
foreach (string x in Vndnbr)
{
command.Parameters["#p1"].Value = x;
command.ExecuteNonQuery();
}
}
}
I have changed you code to include the using statement to correctly close and dispose the connection and the command, then I have initialized the command outside the loop, passed a common string with as a parameter placeholder and initialized this parameter with a dummy value.
Inside the loop I have replaced the previous parameter value with the actual value obtained by your Vndnbr list and executed the command.
You'll want to change your SQL to this:
"insert into Table1 (Vndnbr) Values (#x)";
and then the AddWithValue is like this:
command.Parameters.AddWithValue("#x", ReadFromFile("filepath"));
All you're doing is saying, for this parameter name, I want this value assigned.

Categories