2016-07-28 88 views
-1

我是C#的新手,需要创建一个小表单应用程序,它有两个文本框,一个请求[File_ID],然后当按钮是按下将该号码发送到查询,并在另一个文本框中显示输出。C#按钮,将文本从一个文本框添加到另一个基于SQL查询的文本框

我一直在玩弄它,并有类似的东西。但它不起作用。我不确定我是否应该走另一个方向。我将衷心感谢您的帮助。

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Data.SqlClient; 

namespace testing 
{ 
    public partial class Form1 : Form 
    { 
     String str,dr; 
     SqlConnection con = new SqlConnection("Data Source=USHOU2016\\USFi;Initial Catalog=HOU_2016_Project;Integrated Security=True"); 
     SqlCommand cmd; 
     public Form1() 
     { 
      InitializeComponent(); 

     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      con.Open(); 
      str = "SELECT TOP 1,[Sender Name],[Subject] from [OLE DB Destination] WHERE [CHAT #] ='" + textBox1.Text + "'"; 

      cmd = new SqlCommand(str, con); 
      // dr = cmd.ExecuteReader(); 
      con.Close(); 

     } 

     private void textBox1_TextChanged(object sender, EventArgs e) 
     { 

     } 

     private void textBox2_TextChanged(object sender, EventArgs e) 
     { 
      textBox1.Text = cmd.ExecuteScalar().ToString(); 

     } 


    } 
} 

回答

0

您的SQL查询语法错误,它应该在下面。你有一个额外的,TOP 1后..删除

SELECT TOP 1 [Sender Name],[Subject] from [OLE DB Destination] WHERE... 

再在你的按钮点击你刚刚创建的命令cmd = new SqlCommand(str, con);但从来没有执行它。并关闭连接。

textBox2_TextChanged事件处理程序中,您试图执行查询但连接已经消失。我认为您应该考虑阅读关于ADO.NET的时间了。

+0

谢谢。我将只需要C#作为一种工具,以表格格式输出我的SQL数据。我将如何执行cmd = new SqlCommand(str,con);我需要添加任何东西到文本框1? –

0

这应该可以做到。一对夫妇的注意事项:

  1. 因为按钮被执行你的SQL和填充第二个文本框,没有必要为textbox_changed事件

  2. 使用字符串连接到您的变量添加到您的SQL查询是不好的做法,并使您的代码易受Sql注入的影响。相反,参数化你的sql输入,如下面的代码所示。

    public partial class Form1 : Form 
    { 
    public Form1() 
    { 
        InitializeComponent(); 
    } 
    
    private void button1_Click(object sender, EventArgs e) 
    { 
        string query = "SELECT TOP 1,[Sender Name],[Subject] " 
            + " from[OLE DB Destination] WHERE[CHAT #] = :chatId "; 
        using (SqlConnection con = new SqlConnection("Data Source=USHOU2016\\USFi;Initial Catalog=HOU_2016_Project;Integrated Security=True")) 
        { 
         SqlCommand cmd = new SqlCommand(query, con); 
         cmd.Parameters.AddWithValue("chatId", textBox1.Text); //use Sql parameters to protect yourself against Sql Injection! 
         con.Open(); 
    
         SqlDataReader reader = cmd.ExecuteReader(); 
    
         if (reader.HasRows) 
         { 
          reader.Read(); 
          textBox2.Text = reader[0] + " " + reader[1]; //or however you want your output formatted 
         } 
    
         reader.close(); 
        } 
    } 
    } 
    
相关问题