StarsFlyFree FromCozyNights StarsFlyFree FromCozyNights - 24 days ago 10
C# Question

Compile Errors Using SQLConnection

My syntax shows these errors:


The name 'command' does not exist

The name 'conn' does not exist


I am declaring both of these variables, why am I getting errors? Here is full syntax.

namespace SQLDataPull
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
SQL.DataTable dtData = new SQL.DataTable();
string conString = @"Server=ProdDev;Database=Test;Integrated Security=SSPI;";
StringBuilder query = new StringBuilder();
SQL.DataTable dtProducts = new SQL.DataTable();
query.Append("SELECT Top 1 [saleID] FROM [dbo].[saleorderitems] ORDER BY [saleID] ASC");
//Populating datatable1 with the saleID
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlDataAdapter da = new SqlDataAdapter(query.ToString(), cn))
da.Fill(dtProducts);
}
//Iterating the saleid from datatable
foreach (DataRow row in dtProducts.Rows)
{
using (SqlConnection conn = new SqlConnection("Server=ProdDev;Database=Test;Integrated Security=SSPI;")
{
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM [dbo].[master] WHERE saleID = @saleID;";
command.Parameters.Add("@saleID", SqlDbType.VarChar);
command.Parameters["@saleID"].Value = row.Field<string>("saleID");
command.Connection = conn;
using (SqlDataAdapter dataadapter1 = new SqlDataAdapter()
{
dataadapter1.Fill(dtData);
}
}
}
}
}
}

Answer

You forget closing brackets ) at 2 places

using (SqlConnection conn = 
       new SqlConnection("Server=ProdDev;Database=Test;Integrated Security=SSPI;"))

and

using (SqlDataAdapter dataadapter1 = new SqlDataAdapter())