C# Error: "Fill: SelectCommand.Connection property has not been initialized." - c#

I'm using this video to try and populate results from a DataGridView, and am receiving the above error. The below code pertains to this error - I pass values into a stored procedure, then the final SELECT returns the values in the table in the DataGridView.
SqlConnection con = new SqlConnection();
con.ConnectionString = "integrated security=SSPI;data source=SERV;" + "persist security info=False;initial catalog=DB";
con.Open();
SqlCommand select = new SqlCommand("SELECT * FROM Table");
SqlCommand enter = new SqlCommand("sp_Proc", con);
// Stored Procedure
enter.CommandType = CommandType.StoredProcedure;
enter.Parameters.Add(new SqlParameter("#vvalue", SqlDbType.VarChar)).Value = Convert.ToString(txt1.Text);
enter.Parameters.Add(new SqlParameter("#dvalue", SqlDbType.Decimal)).Value = Convert.ToDecimal(txt2.Text);
enter.ExecuteNonQuery();
// DataGrid returns the SELECT
SqlDataAdapter sadapt = new SqlDataAdapter(select);
sadapt.SelectCommand = select;
DataTable dtab = new DataTable();
sadapt.Fill(dtab); // generates the error
BindingSource b = new BindingSource();
b.DataSource = dtab;
dGrid.DataSource = b;
sadapt.Update(dtab);
con.Close();

You did not pass connection object on the command. Try this instead,
SqlCommand select = new SqlCommand("SELECT * FROM Table", con);

You are passing connection object to your enter command but didnt pass the connection object to your select command
SqlCommand select = new SqlCommand("SELECT * FROM Table");
SqlCommand enter = new SqlCommand("sp_Proc", con);
Use this
SqlCommand select = new SqlCommand("SELECT * FROM Table",con);

SqlCommand cmd = new SqlCommand("sp_StockAnalysis2") // connection missing in sqlcommand
SqlCommand cmd = new SqlCommand("sp_StockAnalysis2",Connection())// pass connection

Related

Gridview datasource from database stored procedure

This is the database stored procedure:
ALTER PROCEDURE [dbo].[getShift]
#rfiddata VARCHAR(50)
AS
BEGIN
SELECT
pd.TP, s.s_name, dt.dt_type, dr.dr_date
FROM
TA_System_PersonalDetails pd
INNER JOIN
TA_System_DutyRequest dr ON pd.TP = DR.TP
INNER JOIN
TA_System_Duty d ON dr.d_ID = d.d_ID
INNER JOIN
TA_System_Shift s ON d.s_ID = s.s_ID
INNER JOIN
TA_System_DutyType dt ON d.dt_ID = dt.dt_ID
WHERE
pd.rfid_card = #rfiddata
AND dr.dr_date = CAST(GETDATE() AS DATE)
END
And this the C# code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("dbo.getShift", con);
cmd.Parameters.AddWithValue("#rfiddata", data);
cmd.CommandType = CommandType.StoredProcedure;
gvDetails.DataSource = cmd.ExecuteNonQuery();
con.Close();
The gridview still not able to show the value. And this project is in windows form C#. Hence, there is no DataBind() function. Thanks in advance for the help!
I hope this code will help
First we create a connector to connect to the database
string cnStr = #"Persist Security Info=False;User ID=usr;password=pwe; Initial Catalog=theDataBase;Data Source=yourDatasource";
and create a SqlCommand and after set the CommandType to StoredProcedure:
SqlCommand cmd = new SqlCommand();
Then create a SqlConnection and Open Database:
using(SqlConnection con = new SqlConnection(cnStr))
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "dbo.getShift"; // this is the stored procedure to execute
cmd.CommandType = CommandType.StoredProcedure;
}//Connection automatically closes here without the need to call conn.Close()
Then create a dataset to be filled as the datasource for the gridview:
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
grdYourGrid.DataSource = ds;
grdYourGrid.DataBind();

Database update error with SQL Server 2012 and C#

I am trying to update my data in a SQL Server database through C#. I am getting updated. But the problem is the data is updated twice.
For example I have 10 (int) in my balance and if I add another 10, it turns to 30.
Any help would be appreciated.
Here is my code:
protected void LoginClick(object sender, EventArgs e)
{
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
}
I would like to rectify few mistakes in your code,
DataTable is not needed to execute the update query, ExecuteNonQuery will do the job
The adapter.Fill and ExecuteNonQuery do the same job here and that's why your updates happening twice
Make use of parameterization while dealing with user inputs to avoid exceptions
For parsing integers use int.TryParse instead for Convert.ToInt32
I think the following code would help you to do the same function in a smarter way:
int currentBalance = 0;
if(int.TryParse(txtAdd.Text, out currentBalance))
{
string querSql = "Update [Order] set Balance = Balance + #balance," +
" Card = #card where email = #email"
using (SqlConnection dbConn = new SqlConnection("connectionString here"))
{
dbConn.Open();
using (SqlCommand sqlCommand = new SqlCommand(querySql, dbConn))
{
sqlCommand.Parameters.Add("#balance", SqlDbType.int).value = currentBalance;
sqlCommand.Parameters.Add("#card", SqlDbType.VarChar).value = card.Text;
sqlCommand.Parameters.Add("#email", SqlDbType.VarChar).value = email;
sqlCommand.ExecuteNonQuery();
}
}
}
Please note: YOu are parsing the balance as an integer value, so I assume the column Balance is an integer field in the database, if not make use of corresponding datatype for the parameter #balance also update the parsing technique
As per the documentation:
SqlDataAdapter(SqlCommand)
Initializes a new instance of the SqlDataAdapter class with the specified SqlCommand as the SelectCommand property.
What is going wrong in your code?
Actually you are passing SqlDataAdapter your update query as the Select command. So now when you will use this instance of SqlDataAdapter to Fill your datatable then actually you are executing your Update command. Look at the following code along with comments to see what is going wrong:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);//The Select command for SqlDataAdapter
//is actually now the update command specified by cmd instnace of SqlCommand
DataTable dt = new DataTable();
sda.Fill(dt);//here SqlDataAdapter will execute it's Select command which is actually set
//to an update statement so your record will be updated
int i = cmd.ExecuteNonQuery();//and here again the update command is being executed now
//directly using the SqlCommand cmd instance and thus your record gets updated twice
con.Close();
Fixed Code:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
//Create a new SqlComamnd
SqlCommand selectCommand = new SqlCommand("Select * from [Order]");
//Put the newly created instance as SelectCommand for your SqlDataAdapter
SqlDataAdapter sda = new SqlDataAdapter(selectCommand);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
Hope this help and do have a look at the documentation for better understanding of the SqlDataAdapter and DataTable. Thanks.

Populate textbox with selected items from database

private void fillProduct() {
SqlConnection conn = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
conn.Open();
string query = "Select prodID from product";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0) {
cmbPCode.DataSource = dt;
cmbPCode.DisplayMember = "prodID";
cmbPCode.ValueMember = "prodID";
}
private void cmbPCode_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
con.Open();
string query = "Select * from product where prodID = '"+cmbPCode.Text+"'".ToString();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
tbdc.Text = dr["prodDescription"].ToString();
}
}
i am having trouble with getting my items from the database according to the selected index i get this error
Conversion failed when converting the varchar value
'System.Data.DataRowView' to data type int
can someone please help me how to convert SqlDataReader to String. because i notice that when i retrieve a column with varchar/string datatype i am not having this kind error but if i retrieve a column with int datatype i get this error.
Replace This:
string query = "Select * from product where prodID = '"+cmbPCode.Text+
"'".ToString();
With This:
string query = "Select * from product where prodID = "+cmbPCode.Text;
Suggestion: Your query is open to SQL Injection i would suggest you to use parameterised queries to avoid them.
Using Parameterised Queries:
string query = "Select * from product where prodID = #ID";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID",cmbPCode.Text);

Add multiple parameters - string values

I have for example this sql command:
string strediska="0003,0005";
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection("****");
cmd = new SqlCommand("select code from table where stred in (#strediskac)", con);
cmd.Parameters.Add(new SqlParameter("#strediskac", strediska));
But result is not right. Have you any idea how I could insert more values in one "variable"?
NOW its OK! Thanks for help. My solution:
cmd = new SqlCommand("select code from table where stred in ("+ strediska +")",con);

error when merging three tables

i'm having an error " Object reference not set to an instance of an object. "
// Define the ADO.NET objects.
SqlConnection con = new SqlConnection(connectionString);
string selectSQL = "SELECT * FROM tbl_lecturer_project";
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dsPubs = new DataSet();
// Try to open database and read information.
try
{
con.Open();
adapter.Fill(dsPubs, "tbl_lecturer_project");
// This command is still linked to the data adapter.
cmd.CommandText = "SELECT * FROM tbl_student_project_choice";
adapter.Fill(dsPubs, "tbl_student_project_choice");
cmd.CommandText = "SELECT * FROM tbl_team";
adapter.Fill(dsPubs, "tbl_team");
DataRelation SCoiceLec = new DataRelation("SCoiceLec", dsPubs.Tables["tbl_lecturer_project"].Columns["lecturerProjectId"], dsPubs.Tables["student_project_choice"].Columns["choiceProjectId"]);
DataRelation SChoiceNTeam = new DataRelation("SChoiceNTeam",dsPubs.Tables["student_project_choice"].Columns["choiceGroupId"], dsPubs.Tables["tbl_team"].Columns["teamId"]);
please help. i want to retrieve data from all 3 tables.
There are a number of problems with your code. Here is one:
adapter.Fill(dsPubs, "tbl_lecturer_project");
should be
adapter.Fill(dsPubs);
I think what you want is this:
string selectSQL = #"SELECT * FROM tbl_lecturer_project;
SELECT * FROM tbl_student_project_choice;
SELECT * FROM tbl_team";
using(SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(selectSQL, con))
{
using(SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
DataSet dsPubs = new DataSet();
adapter.Fill(dsPubs);
// use dataset.
}
}
}
The three tables will have the names Table, Table1, and Table2

Categories