none
How to load a particular row RRS feed

  • Question

  • I am developing an app using C# I need Sql syntax that will load a particular row from the table. The row to be loaded will be chosen from a ListBox
    • Edited by Roger Rios Jr Sunday, December 21, 2014 2:42 AM
    • Moved by Bob Beauchemin Sunday, December 21, 2014 4:12 AM Moved to the forum for client-side SqlClient code
    Sunday, December 21, 2014 2:41 AM

Answers

  • Please try to use the following syntax

     SqlConnection con = new SqlConnection("ConnectionString");
    
                try
                {
                    con.Open();
    
                    SqlCommand com = new SqlCommand("SELECT * FROM myTable WHERE myColumn='" + listBox1.SelectedItem.ToString() + "'", con);
                    com.CommandType = CommandType.Text;
                    com.ExecuteNonQuery();
    
                }
                catch (SqlException sql) { System.Windows.Forms.MessageBox.Show(sql.Message); }
                finally
                {
                    if (con.State == ConnectionState.Open)
                    {
                        con.Close();
                        con.Dispose();
                    }
                }

    • Marked as answer by Roger Rios Jr Monday, December 22, 2014 8:51 PM
    Sunday, December 21, 2014 2:30 PM

All replies

  • Please try to use the following syntax

     SqlConnection con = new SqlConnection("ConnectionString");
    
                try
                {
                    con.Open();
    
                    SqlCommand com = new SqlCommand("SELECT * FROM myTable WHERE myColumn='" + listBox1.SelectedItem.ToString() + "'", con);
                    com.CommandType = CommandType.Text;
                    com.ExecuteNonQuery();
    
                }
                catch (SqlException sql) { System.Windows.Forms.MessageBox.Show(sql.Message); }
                finally
                {
                    if (con.State == ConnectionState.Open)
                    {
                        con.Close();
                        con.Dispose();
                    }
                }

    • Marked as answer by Roger Rios Jr Monday, December 22, 2014 8:51 PM
    Sunday, December 21, 2014 2:30 PM
  • Below is a parameterized example of the method Doanh, OH suggested.  Parameterized queries instead of string concatenation are a best practice.  This example returns the result as a DataTable with a single row.

    SqlCommand com = new SqlCommand("SELECT * FROM sys.MyTable WHERE name = @name;", con);
    com.CommandType = CommandType.Text;
    com.Parameters.Add("@name", SqlDbType.VarChar, 30).Value = listBox1.SelectedItem.ToString();
    var da = new SqlDataAdapter(com);
    var dt = new DataTable();
    da.Fill(dt);


    Dan Guzman, SQL Server MVP, http://www.dbdelta.com

    Sunday, December 21, 2014 2:53 PM