ERROR with SQL Server database connectivity - c#

Basically I am trying to develop a software and I am new in programming. I am trying to insert the data of textbox into SQL Server 2008 R2 Standard and I am getting an error:
System.NullReferenceException was unhandled
Here is my code.
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=(local);Initial Catalog=songs_db;Persist Security Info=True;User ID=sa;Password=iloveyourb";
con.Open();
DataSet ds = new DataSet();
String sql = "Select * From tbl_songdb";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataRow drow = ds.Tables["tbl_songdb"].NewRow(); // I am getting error message here.
drow[1] = txt_songName.Text;
drow[2] = txt_minute.Text;
drow[3] = txt_albumnName.Text;
drow[4] = txt_location.Text;
ds.Tables["tbl_songdb"].Rows.Add(drow);
con.Close();

actually my dataset was empty, thats why it was showing NULL error
da.Fill(ds, "tbl_studentData");
i used these lines to fill it and now everything is working fine.
thanks to all for giving their time.

Just do exactly what error said to you. Handle it with try catch like that:
try{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=(local);Initial Catalog=songs_db;Persist Security Info=True;User ID=sa;Password=iloveyourb";
con.Open();
DataSet ds = new DataSet();
String sql = "Select * From tbl_songdb";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataRow drow = ds.Tables["tbl_songdb"].NewRow(); // I am getting error message here.
drow[1] = txt_songName.Text;
drow[2] = txt_minute.Text;
drow[3] = txt_albumnName.Text;
drow[4] = txt_location.Text;
ds.Tables["tbl_songdb"].Rows.Add(drow);
da.Update(ds);
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}

SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=(local);Initial Catalog=songs_db;Persist Security Info=True;User ID=sa;Password=iloveyourb";
con.Open();
DataSet ds = new DataSet();
String sql = "Select * From tbl_songdb";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(ds);
DataRow drow = ds.Tables[0].NewRow(); // I am getting error message here.
drow[1] = txt_songName.Text;
drow[2] = txt_minute.Text;
drow[3] = txt_albumnName.Text;
drow[4] = txt_location.Text;
ds.Tables[0].Rows.Add(drow);
SQLiteCommandBuilder cmdbuilder = new SQLiteCommandBuilder(da);
da.InsertCommand = cmdbuilder.GetInsertCommand();
da.Update(ds);
ds.AcceptChanges();
con.Close();

Related

How to Reuse Logic Without Copy/Pasting Blocks of Code - C#

My project reuses the code below multiple times with only a few variables changing. I've noted the values that change with e.g. ***value***.
if (comboBox1.Text == ***"Most recent first"***)
{
string dgvconn = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\CW\CW\bin\Debug\Database1.mdf;Integrated Security=True";
string sql = "select * from Records where UserID = #userID Order By ***Date Desc***";
SqlConnection connection = new SqlConnection(dgvconn);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
dataadapter.SelectCommand.Parameters.AddWithValue("#userID", currentUserID);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Records");
connection.Close();
recordsDataGridView.DataSource = ds;
recordsDataGridView.DataMember = "Records";
}
How can I use this same logic, with different values, without copying and pasting the if statement multiple times?
Sounds to me you want something like:
private void foo(string matchText, string sortBy) {
if (comboBox1.Text == matchText)
{
string dgvconn = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\CW\CW\bin\Debug\Database1.mdf;Integrated Security=True";
string sql = "select * from Records where UserID = #userID Order By " + sortBy;
SqlConnection connection = new SqlConnection(dgvconn);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
dataadapter.SelectCommand.Parameters.AddWithValue("#userID", currentUserID);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Records");
connection.Close();
recordsDataGridView.DataSource = ds;
recordsDataGridView.DataMember = "Records";
}
}//foo
//Call the method
foo("Most recent first", "Date DESC");
foo("Most recent last", "Date");
foo("By Username", "User");

Assign query result into a session

i want assign result into a session
c# code
protected void BindData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-677TN4G\SQLEXPRESS;Initial Catalog=homework;Persist Security Info=True;User ID=sa;Password=123456");
DataSet ds = new DataSet();
DataTable FromTable = new DataTable();
con.Open();
string cmdstr = "Select CourseName from Staff where FacultyNumber=#idd";
SqlCommand cmd = new SqlCommand(cmdstr, con);
cmd.Parameters.AddWithValue("#idd", Session["id"].ToString());
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
DataList1.DataSource = ds.Tables[0];
DataList1.DataBind();
}
so how i can do it i try to do
Session["id"] = cmdstr.Text;
but it not work
i do it like this but not work
I do it like this
protected void BindData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-677TN4G\SQLEXPRESS;Initial Catalog=homework;Persist Security Info=True;User ID=sa;Password=123456");
DataSet ds = new DataSet();
DataTable FromTable = new DataTable();
con.Open();
string cmdstr = "Select CourseName from Staff where FacultyNumber=#idd";
SqlCommand cmd = new SqlCommand(cmdstr, con);
cmd.Parameters.AddWithValue("#idd", Session["id"].ToString());
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
DataList1.DataSource = ds.Tables[0];
Session.Add("Staff", ds.Tables[0]);
DataList1.DataBind();
Label1.Visible = true;
Label1.Text = "Course Name is : " + Session["Staff"].ToString();
}
and the output is
Course Name is : Table
not the selected value
In your case the result is a DataTable no problem you can store this DataTable to the session as well. Let staffData be the DataTable that you are populating from the database,
Session.Add("Staff", staffData); // Adding datatable to the session
In your case you are using ds is used as a DataSet and you are accessing ds.Tables[0] to bind the grid. in this case you can use something like: Session.Add("Staff", ds.Tables[0]);.
Later you may come up with another question that how can I retrieve this DataTable from the session, Here I'm adding the answer for that as well.
DataList1.DataSource = (DataTable)Session["Staff"];

C# .mdf connection failed

I am facing the following problem in my VS 2013
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Here is the code:
SqlConnection myConnection = new SqlConnection("Data Source =.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\\Database1.mdf; Integrated Security = True; User Instance = True;");
myConnection.Open();
SqlCommand myCommand = myConnection.CreateCommand();
myCommand.CommandType = CommandType.Text;
myCommand.CommandText = "SELECT * FROM Customer";
SqlDataAdapter myDataAdapter = new SqlDataAdapter(myCommand);
DataSet myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet);
myConnection.Close();
foreach(DataRow myRow in myDataSet.Tables[0].Rows)
{
Console.WriteLine(myRow["FirstName"]+" " +myRow["LastName"]);
}
Console.ReadLine();

ComboBox cannot display new value added

I have added a new value into my combobox and it should be displayed based on what I have in my database. But unfortunately, the new value does not display out. Below are my codes.
string dbConn = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\SONY\\Desktop\\FinalYearProject\\FinalYearProject\\bin\\Debug\\housewife.mdf;Integrated Security=True;User Instance=True";
void fill_Combo() {
SqlConnection conn = new SqlConnection(dbConn);
try {
conn.Open();
string query = "Select * From Food";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
string name = dr.GetString(1);
comboBox1.Items.Add(name);
}
conn.Close();
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
You should be using an observable collection as the data source and binding to that collection. See Add items to comboBox in WPF
Hi please try something like this, hope it helps
string dbConn = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\SONY\\Desktop\\FinalYearProject\\FinalYear Project\\bin\\Debug\\housewife.mdf;Integrated Security=True;User Instance=True";
void fill_Combo() {
SqlConnection conn = new SqlConnection(dbConn);
try {
conn.Open();
string query = "Select * From Food";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds)
combobox1.DataSourse = ds;
combobox1.DisplayMember = "fieldname";
combobox1.ValueMember = "fieldname";
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}

How to get data from SQL database to store in combo box - C#

How can i get the value of company_name from Comp table and store it on a comboBox?
here is my initial code on getting the values from Database and store it on a combobox:
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
it point out to da.fill(ds) and says "Could not locate entry in sysdatabases for database 'select company_name from JO'. No entry found with that name. Make sure that the name is entered correctly."
hope for your reply thanks!
Use datareader it is much simpler \
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(Sql, conn);
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
combobox1.Items.Add(DR[0]);
}
If you set up your connection string to be something of this sort:
string SqlConnectionString = "Data Source=[SERVER];Initial Catalog=[DATABASE];"
Then using that set up, you can set your string 'Sql' as:
string Sql = "select company_name from dbo.Comp";
This could be a possible set up you could use to read out the values.
using (SqlConnection saConn = new SqlConnection(this.ConnectionString))
{
saConn.Open();
string query = "select DBName from dbo.Company";
SqlCommand cmd = new SqlCommand(query, saConn);
using (SqlDataReader saReader = cmd.ExecuteReader())
{
while (saReader.Read())
{
string name = saReader.GetString(0);
combobox1.Add(name);
}
}
saConn.Close();
}
I would like to introduce you a very simple way to SQL data into a combobox as:
first you have a create a SQL table,
in C# platform drop a combobox and go to its property,
in the property menu click on "DataSource"
specify the database and table to load into combobox,
Note, the combobox name and table's row should be the same.
{
SqlConnection con =new SqlConnection("Data Source=Server_Name;Initial Catalog=Database_Name;integrated security=true");
SqlCommand cmd;
SqlDataReader dr;
private void CashMemoForm_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("Select Column_Name From Table_Name", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr[0]).ToString();
}
}
}
Have you ever tried Entity Framework for database access and dto creation?
Change your line to cmd.CommandType = CommandType.Text; instead of cmd.CommandType = CommandType.StoredProcedure;
Try this
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("--Select--", "0"));
}
There is no use of for loop. you just need to check that whether the dataset contains rows or not.
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("Select", "0"));
}
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
public System.Data.DataTable EmployeeViewAll()
{
DataTable dtbl = new DataTable();
try
{
// Here it shuld be your database Connection String
string connectionString = "Server = .; database = HKS; Integrated Security = true";
using (SqlConnection sqlCon = new System.Data.SqlClient.SqlConnection(connectionString))
{
SqlDataAdapter SqlDa = new SqlDataAdapter("employeeViewAll", sqlCon);
SqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlDa.Fill(dtbl);
}
return dtbl;
}
catch (Exception)
{
throw;
}
}
public void ComboFill()
{
DataTable dt = new DataTable();
eSP SP = new eSP();
d = SP.EmployeeViewAll();
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "department";
comboBox1.ValueMember = "empName";
}

Categories

Resources