-2

I have a windows form that I am asking a user to enter a pcname in textbox1 and then trying to use SqlDataReader to the read from the database to get the pc ipaddress and then map the pc drive to my local pc.

But for some reason when I use the textbox within the SQL parameter it's not working. But when I replace the textbox1.text with the actual pcname it works fine. Hopefully someone can help me find out why the parameter isn't working correctly.

Here is my code:

public void button1_Click(object sender, EventArgs e)
{
    string results = "";

    using (SqlConnection cs = new SqlConnection(@"***removed connection string***"))
    {
        cs.Open();

        string query = "select stationipaddress from station where stationname = @StationName";

        using (SqlCommand cmd = new SqlCommand(query, cs))
        {
            // Add the parameter and set its value -- 
            cmd.Parameters.AddWithValue("@StationName", textBox1.Text);

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    label3.Text = dr.GetSqlValue(0).ToString();
                    results = dr.GetValue(0).ToString();
                    MessageBox.Show(dr.GetValue(0).ToString());
                    MessageBox.Show(results);
                }

                string myvar = string.Format(@"use S: \\" + label3.Text + "\\c$\logs 0A36303 /user:admin", label3.Text);

                Process p = new Process();
                p.StartInfo.FileName = "net.exe";
                p.StartInfo.Arguments = (myvar);
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.CreateNoWindow = true;
                p.Start();
tomfanning
  • 9,552
  • 4
  • 50
  • 78
user1836162
  • 59
  • 2
  • 4
  • 14

1 Answers1

0

Maybe if you separate you code in different lines, one to set up your parameter, and one to add it, you can better see where the problem is. Something like this:

SqlParameter param1 = new SqlParameter("@StationName", SqlDbType.NVarChar, textBox1.Text.length);
param1.Value = textBox1.Text;
cmd.Parameters.Add(param1);

at least is easier to see what is going on on the debugger.

Julio Garcia
  • 1,904
  • 16
  • 26
  • When I put the stationname in the query like this: 'stationname' it works but doesn't with a parameter, does this have something to do with it? – user1836162 Nov 30 '12 at 16:50
  • When using mssql you use single quotes in a sql statement to denote a string. In c# single quotes denote char type not a string. – Julio Garcia Dec 01 '12 at 09:05