Cant read from SQL Server database in C# - c#

I am currently working on a college assignment in which I am having trouble reading data from a SQL Server database. I'm attempting to read the Dentist Name column and then add these names to a combobox.
However when I input the column name it shows an error.
My table is called dentistInfo with columns Dentist ID, Dentist Name, Dentist Surname, DOB and Gender.
Eventually when I get to the reading done correctly I will then hopefully be able to populate their details when the names are selected from the combobox.
public partial class Dentist_Info : Form
{
Surgery mySurgery = new Surgery();
private SqlConnection conn;
private SqlCommand cmd;
private SqlDataAdapter da;
Surgery _formsSurgery;
public Dentist_Info(Surgery SurgeryToDisplay)
{
_formsSurgery = SurgeryToDisplay;
}
public void FillCombo()
{
SqlConnection conn = new SqlConnection(#"Data Source = GGJG; Initial Catalog = DentistDB; Integrated Security = True");
SqlCommand SelectCommand = new SqlCommand("SELECT * FROM DentistInfo", conn);
SqlDataReader myreader;
conn.Open();
try
{
myreader = SelectCommand.ExecuteReader();
while (myreader.Read())
{
string dname = myreader.GetString("Dentist Name");
comboBox1.Items.Add(dname);
}
conn.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}

Pro-tip: If you want to ask about an error, post the error.
In any case, the problem is easy to spot in this case. There's no overload of GetString that accepts a string as an argument - you can only use the column index.
So either you need to pass the column index (myreader.GetOrdinal("Dentist Name")) or you need to use the indexer ((string)myreader["Dentist Name"]). In either case, make sure to handle possible NULL values properly - data reader simply throws an exception if you try to read an SQL NULL value.
As an aside, your try...catch can be simplified (and more useful):
When you want to rethrow an exception, use throw; (no "argument"). Wrap the exception only if you have some information to add.
The catch clause isn't required. It seems that you're only using it for the finally - it's perfectly fine to just use try...finally without the catch.
conn can never be null in the finally clause - your try isn't long enough.
For a pattern like this, you want to use using instead of try...finally anyway. You should also use using for the data reader.

Try this: I recommend you putting [] in the Dentist Name since it has a space between the two words, which might cause you the error, or change the name from the Database to DentistName
public void FillCombo()
{
SqlConnection conn = new SqlConnection(#"Data Source = GGJG; Initial Catalog = DentistDB; Integrated Security = True");
SqlCommand SelectCommand = new SqlCommand("SELECT * FROM DentistInfo", conn);
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(SelectCommand);
da.fill(ds);
foreach(DataRow dr in ds.Tables[0].Rows)
{
comboBox1.Items.Add(dr["[Dentist Name]"].ToString());
}
conn.Close();
}
As per addition instead of using conn.Open() and conn.Close(), as the answer of the first user you can surround the connection inside a using like so:
using(SqlConnection conn = new SqlConnection(#"Data Source = GGJG; Initial Catalog = DentistDB; Integrated Security = True"))
{
//your codes here no need for conn.Open() and conn.Close()
}

Related

How to insert data into local database using C#

I am working on my first project using local database on C#. I have searched on internet different code for inserting data, but nothing has worked for me. I am trying different code, the problem that occurs to me is the built in functions they are using doesn't show up in my code. Can someone share the authentic code for inserting, retrieving and deleting in local database ?
The recent code that I have tried, some exception is occurring in SqlCeConnection.
This is my code :
string str="Data Source=(localdb)shop_database;Initial Catalog=shop_database;Integrated Security=True";
SqlCeConnection con = new SqlCeConnection(str);
SqlCeDataAdapter sda = new SqlCeDataAdapter();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "Insert into Account_details (Account_No,Customer_name,Customer_father_name,Profession,Mobile_No,Office_Address,House_Address,CNIC,Item_name,Item_color,Item_model,Item_engine_NO,Item_chasis_NO,Cash_price,Installment_price,Advance_given,Amount_left,Monthly_Installment,Monthly_Rent,Date_of_giving,Sponsor_name,Sponsor_father_name,Sponsor_profession,Sponsor_Address,Sponsor_CNIC,Sponsor_Mobile_No) values (#Account_No,#Customer_name,#Customer_father_name,#Profession,#Mobile_No,#Office_Address,#House_Address,#CNIC,#Item_name,#Item_color,#Item_model,#Item_engine_NO,#Item_chasis_NO,#Cash_price,#Installment_price,#Advance_given,#Amount_left,#Monthly_Installment,#Monthly_Rent,#Date_of_giving,#Sponsor_name,#Sponsor_father_name,#Sponsor_profession,#Sponsor_Address,#Sponsor_CNIC,#Sponsor_Mobile_No)";
cmd.Parameters.AddWithValue("#Account_No", this.Textbox0.Text);
cmd.Parameters.AddWithValue("#Customer_name", this.Textbox1.Text);
cmd.Parameters.AddWithValue("#Customer_father_name", this.Textbox2.Text);
cmd.Parameters.AddWithValue("#Profession", this.Textbox3.Text);
cmd.Parameters.AddWithValue("#Mobile_No", this.Textbox4.Text);
cmd.Parameters.AddWithValue("#Office_Address", this.Textbox5.Text);
cmd.Parameters.AddWithValue("#House_Address", this.Textbox6.Text);
cmd.Parameters.AddWithValue("#CNIC", this.Textbox7.Text);
cmd.Parameters.AddWithValue("#Item_name", this.Textbox14.Text);
cmd.Parameters.AddWithValue("#Item_color", this.Textbox15.Text);
cmd.Parameters.AddWithValue("#Item_model", this.Textbox16.Text);
cmd.Parameters.AddWithValue("#Item_engine_NO", this.Textbox17.Text);
cmd.Parameters.AddWithValue("#Item_chasis_NO", this.Textbox18.Text);
cmd.Parameters.AddWithValue("#Cash_price", this.Textbox19.Text);
cmd.Parameters.AddWithValue("#Installment_price", this.Textbox20.Text);
cmd.Parameters.AddWithValue("#Advance_given", this.Textbox21.Text);
cmd.Parameters.AddWithValue("#Amount_left", this.Textbox25.Text);
cmd.Parameters.AddWithValue("#Monthly_Installment", this.Textbox22.Text);
cmd.Parameters.AddWithValue("#Monthly_Rent", this.Textbox23.Text);
cmd.Parameters.AddWithValue("#Date_of_giving", this.Textbox24.Text);
cmd.Parameters.AddWithValue("#Sponsor_name", this.Textbox8.Text);
cmd.Parameters.AddWithValue("#Sponsor_father_name", this.Textbox9.Text);
cmd.Parameters.AddWithValue("#Sponsor_profession", this.Textbox10.Text);
cmd.Parameters.AddWithValue("#Sponsor_Address", this.Textbox11.Text);
cmd.Parameters.AddWithValue("#Sponsor_CNIC", this.Textbox12.Text);
cmd.Parameters.AddWithValue("#Sponsor_Mobile_No", this.Textbox13.Text);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
To edit, insert, in general interact with your database you need the class SqlCommand. First you create a connection to your database with an SqlConnection object. Then you pass the SQL statement as a string and the connection into the constructor of the SqlConnection class. Little example:
SqlConnection con = new SqlConnection("server=localhost;database=test_db;uid=root;password=yourpassword");
SqlCommand cmd = new SqlCommand("select * from your_table", con);
To retreive the data from the database you need to use the SQL Statements. For example an SQL statement is something like:
insert into my_table (value1, value2)
values("Example", "Insertion");
When you created your SqlConnection and the SqlCommand you need to open the database connection and execute the command. Wether it's a command for receiving information from the database or editing the database you use ExecuteReader() or ExecuteNonQuery(). For example when you want to receive all the Information stored in one table you use:
SqlConnection con = new SqlConnection("connection string as shown above");
SqlCommand cmd = new SqlCommand("select * from example_table", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
Console.WriteLine(reader[<table_index or attribute Name>]);
And finally dont forget to call the close method on your SqlConnection and SqlDataReader object
You are probably making two mistakes:
Problem 1. Your connecting string looks like wrong. Instead of:
Data Source=(localdb)shop_database;Initial Catalog=shop_database;Integrated Security=True";
It should be:
Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=shop_database;Integrated Security=True";
Problem 2. You are not opening the connection before executing the command. Your code in the block should be like this:
try
{
conn.Open(); // Open the connection
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close(); // Close the connection
}
As a best practice, I recommend that you use "using" block to create your connection. In that case, you don't have to explicitly close the connection and set it to null:
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
conn.Open();
// Remaining code
}
}
catch(Exception ex)
{
// Manage your exception here
}

Cannot add data into database in visual c#

As a beginner to c#, and I actaully spent a lot of time researching this:
I cannot add some data into the database, I can extract data from it, but cannot add anything into the database. I use sql server as my database.
try {
fname = fname_tb.Text;// first name
sname = sname_tb.Text; // second name
q = "insert into beforebath1(firstname,secondname) values(#fname,#sname)";
conn_string = Properties.Settings.Default.beforebath_connection_string;
SqlConnection co = new SqlConnection(conn_string);
SqlCommand cmd;
co.Open();
cmd = new SqlCommand(q, co);
cmd.Connection = co;
cmd.Parameters.AddWithValue("#fname", fname_tb.Text);
cmd.Parameters.AddWithValue("#sname", sname_tb.Text);
cmd.ExecuteNonQuery();
co.Close();
}
catch(Exception err) {
MessageBox.Show(err.toString());
}
my sql connection string is this:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\beforebath_db.mdf;Integrated Security=True;Connect Timeout=30
It is automatically generated when I created the database. Please help me insert the text in the two textboxes (fname_tb.Text and sname_tb.Text) into the table called beforebath1 of the database called beforebath_db.mdf.
Is it something to do with my data directory?
I see a couple of mistakes in your code.
First, why catch an exception that will only be shown in a message?
It is often best to let the exception bubble up to have the stack trace in debug. This is not the same if this is production code, which I doubt.
Second, make sure to dispose your objects adequately.
The Using Statement is the most prefered way to work with disposeable items such as a database connection and a command.
using (var cnx = new SqlConnection(connectionString)) {
cnx.Open();
var sql = #"insert into beforebath1 (first_name, second_name)
values (#fname, #lname)";
using (var cmd = new SqlCommand(sql, cnx)) {
cmd.Parameters.AddWithValue("#fname", fname_tb.Text);
cmd.Parameters.AddWithValue("#lname", lname_tb.Text);
try {
int rowsAffected = cmd.ExecuteNonQuery();
if (0 < rowsAffected) MessageBox.Show("Success!");
else MessageBox.Show("Failed!");
} catch (SqlException ex) {
// It is almost prefered to let the exception be thrown freely
// so that you may have its full stack trace and have more
// details on your error.
MessageBox.Show(ex.Message);
} finally {
if (cnx.State == ConnectionState.Open) cnx.Close();
}
}
}
This way, wrapping your disposable objects within using blocks, you make sure that everything is getting to get disposed automatically when exiting the code block.
As for your "it doesn't work" problem, I guess the problem be either at the connection string level, or at your table_name level.
You wish to insert into beforebath1, and your insert statement states table_name. Make sure you put the right table name where it belongs so that it may work properly.
Can you change you connection string to this:
Server=(LocalDB)\v11.0;Database=beforebath_db;Trusted_Connection=True;
This means the your app and other programs using the Db will all share the same instance.
Also, as mentioned by #Will, you should wrap your SQLConnection in a using statement for garbage collection.
For better implementations you can use stored_procedures like bellow:
Step1: Declare Stored Procedure for your Query:
CREATE PROCEDURE [dbo].[ADD_TO_BEFORE_PATH_SP]
/*Type of this variables should be their column types*/
#fname varchar(MAX),
#lname varchar(MAX)
AS
BEGIN
INSERT INTO [dbo].[beforebath1] (fname, lname)
VALUES (#fname,#lname)
END
Step2: Using Stored Procedure where you need:
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand("ADD_TO_BEFORE_PATH_SP", con);
com.Parameters.AddWithValue("#fname", fname_tb.Text);
com.Parameters.AddWithValue("#lname", lname_tb.Text);
com.CommandType = CommandType.StoredProcedure;
try
{
con.Open();
com.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}

How to fill dropddownlist from databse in .net

below is the code I wrote to fill dropdown list from the database,and I am not getting where I did mistake..help me in finding out and correcting my mistake.
void filldistrict()
{
DropDownList4.Items.Clear();
DropDownList4.Items.Add("--District--");
String q="select * from DLIST";
SqlCommand cmd=new SqlCommand(q,cn);
SqlDataReader rec = cmd.ExecuteReader();
if (rec.Read())
DropDownList4.Items.Add(rec.getValue(1).ToString);
rec.Close();
}
Your code is very close - the only problem is this line:
if (rec.Read())
You can also use new ListItem() when adding to the Items collection. You can use the overload that takes two strings that will set the text and the value, as well.
That will only get the first row of the returned records, not all of them. What you want is to loop through the records in rec, like this:
void filldistrict()
{
DropDownList4.Items.Clear();
DropDownList4.Items.Add("--District--");
String q="select * from DLIST";
SqlCommand cmd=new SqlCommand(q,cn);
using (SqlDataReader rec = cmd.ExectueReader())
{
while (rec.Read())
{
DropDownList4.Items.Add(new ListItem(rec.GetValue(1).ToString()));
}
}
}
Note that I used a using block with the reader so its automatically closed while the block is exited. I would also suggest doing the same with your SqlConnection.
The alternative provided by Ali is also a valid approach.
SqlConnection sql_cnt=new SqlConnection("connectionString");
SqlCommand sql_cmd=new SqlCommand("select * from DLIST",sql_cnt);
Dataset dt_data=new Dataset();
SqlDataAdapter sql_adp=new SqlDataAdapter(cmd);
try
{
sql_cnt.Open();
sql_adp.Fill(dt_data);
sql_cnt.Close();
}
catch(Exception err)
{
//Do something;
}
DropDownList4.ValueMember="the name of the field which you want to be shown in dropdown list";
DropDownList4.DataSource=dt_data;

How to show data using datagrid with C# + SQL Server

I want to ask more to show data from SQL Server to WinForm using a datagrid.
I've been creating a datagrid and the stored procedure to show data is
ALTER PROC [dbo].[SP_GetData]
AS
SELECT nama , nim
FROM tabledata
and I've created the function to access the database and the stored procedure in C#
string Sp_Name = "dbo.SP_GetData";
SqlConnection SqlCon = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBMahasiswa;Data Source=.");
SqlCon.Open();
SqlCommand SqlCom = new SqlCommand(Sp_Name , SqlCon);
SqlCom.CommandType = CommandType.StoredProcedure;
List<mahasiswaData> listMahasiswa = new List<mahasiswaData>();
using (SqlDataReader sqlDataReader = SqlCom.ExecuteReader())
{
if (sqlDataReader.HasRows)
{
while (sqlDataReader.Read())
{
mahasiswaData DataMhs = new mahasiswaData();
DataMhs.Nama = sqlDataReader["Name"].ToString();
DataMhs.Umur = Convert.ToInt32(sqlDataReader["Age"]);
listMahasiswa.Add(DataMhs);
}
}
}
SqlCon.Close();
return listMahasiswa;
and finally, in the show button I add this code
dgvmahasiswa.DataSource = new MahasiswaDB().LoadMahasiswa();
Could somebody tell me where the fault is or the alternatives one?
Thank You So Much! :D
Some things to think about:
At the moment, if your code runs into exceptions, you'll leave a
SqlConnection hanging around; you've used the using pattern for your
SqlDataReader; you should extend it to all of your disposable
objects.
You are swallowing exceptions; if your query fails, the connection
cannot be made, or something else happens, you'll never really know - your function will just return null.
Is it possible for name or age to be null? Age to be non-numeric?
There's no test for any unexpected values, which you'll also never
know about.
If you don't have any records, you'll return an empty list. Is this
desired? Or would you prefer to know there were no records?
You might prefer to look at something like this:
public List<mahasiswaData> GetData(){
List<mahasiswaData> gridData = new List<mahasiswaData>();
try{
using(SqlConnection conn = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBMahasiswa;Data Source=."))
{
using(SqlCommand command = new SqlCommand())
{
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.Text = "dbo.SP_GetData";
using(SqlDataReader reader = command.ExecuteReader())
{
if(reader.HasRows){
while(reader.Read())
{
object rawName = reader.GetValue(reader.GetOrdinal("Name"));
object rawAge = reader.GetValue(reader.GetOrdinal("Age"));
if(rawName == DBNull.Value || rawAge == DBNull.Value)
{
//Use logging to indicate name or age is null and continue onto the next record
continue;
}
//Use the object intializer syntax to create a mahasiswaData object inline for simplicity
gridData.Add(new mahasiswaData()
{
Nama = Convert.ToString(rawName),
Umur = Convert.ToInt32(rawAge)
});
}
}
else{
//Use logging or similar to record that there are no rows. You may also want to raise an exception if this is important.
}
}
}
}
}
catch(Exception e)
{
//Use your favourite logging implementation here to record the error. Many projects use log4Net
throw; //Throw the error - display and explain to the end user or caller that something has gone wrong!
}
return gridData;
}
Note that if you are sure that age or name will never be null then you can simplify the middle section:
while (reader.Read())
{
//Use the object intializer syntax to create a mahasiswaData object inline for simplicity
gridData.Add(new mahasiswaData()
{
Nama = reader.GetString(reader.GetOrdinal("Name")),
Umur = reader.GetInt32(reader.GetOrdinal("Age"))
});
}

C# SQL connection problem

i am using VS.NET 2008 with MS SQL server 2005 to develop a window form application but everytime i got new error in connection or after conected,
in my current code the connection opened but doesnt work after that in transaction of queries. maybe i have problem while making new DB or new datasource also m not that satisfy how to get Connecting String
this is my code....
/////////
private void button1_Click(object sender, EventArgs e)
{
try
{
//setData();
string ConnectingString = #"Data Source=SERVER1\SQLEXPRESS;Initial Catalog=Alkawthar;Integrated Security=True;Pooling=False";
qry = "SELECT * FROM Table1";
//reader = db.select_data(qry);
ds1 = new DataSet();
conn = new SqlConnection(ConnectingString);
conn.Open();
MessageBox.Show("connection opened");
da.Fill(ds1,"Workers");
NavigateRecords();
MaxRows = ds1.Tables["Workers"].Rows.Count;
string sql = "SELECT * From tblWorkers";
da = new System.Data.SqlClient.SqlDataAdapter(sql, conn);
conn.Close();
MessageBox.Show("connection closed");
conn.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("exception");
MessageBox.Show(ex.Message);
}
}
/////////////////
Fill throws an exception also when i use reader it return null although there is data in DB
thanks
The most obvious problem here is that you access the SqlDataAdapter before initializing it. That will cause a null reference exception.
Try to move the line da = new SqlDataAdapter(...) to the line before you do the da.Fill(...).
Edit:
No, wait! I see that you do two queries and two fills in there. You need to initialize the SqlDataAdapter before doing the first fill. Then you should get rid of the null reference exception.
Edit again:
Also, as commented, you don't need call both the SqlConnection.Close and SqlConnection.Dispose methods. As long as you use the SqlDataAdapter you don't even need to do the SqlConnection.Open on the connection, for the Fill method will do all that for you. As long as the connection starts out being closed, the Fill method will close it again for you when it is done.
A few points of advice;
Like Turrau and Rune say, your stuff is in the wrong order. Open connection, Execute SQL - Get raw data, close connection. Then do your counting, etc.
Don't put message box or logging calls anywhere in between the connection opening and closing. This has burned me before, where the those calls can affect the SQL call because they fudge the exception details and make it difficult to trace. This is also applicable when using a SQL data reader.
Put the SQL stuff in a using block.
Try this...
string _connStr = #"Data Source=SERVER1\SQLEXPRESS;Initial Catalog=Alkawthar;Integrated Security=True;Pooling=False";
string _query = "SELECT * FROM Workers";
DataSet _ds = new DataSet();
try
{
using (SqlConnection _conn = new SqlConnection(_connStr))
{
SqlDataAdapter _da = new SqlDataAdapter(_query, _conn);
_conn.Open();
_da.Fill(_ds);
}
// insert null dataset or invalid return logic (too many tables, too few columns/rows, etc here.
if (_ds.Tables.Count == 1)
{ //There is a table, assign the name to it.
_ds.Tables[0].TableName = "tblWorkers";
}
//Then work with your tblWorkers
}
catch (Exception ex)
{
Console.Write("An error occurred: {0}", ex.Message);
}
Seems to me, that you use your DataAdapter before initialization. Do you get a NullReferenceException?
da.Fill(ds1,"Workers");
// ...
da = new System.Data.SqlClient.SqlDataAdapter(sql, conn);

Categories

Resources