Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从文本框读取sql字符串并显示在datagridview中_C#_Sql_Datagridview_Textbox_Windows Forms Designer - Fatal编程技术网

C# 从文本框读取sql字符串并显示在datagridview中

C# 从文本框读取sql字符串并显示在datagridview中,c#,sql,datagridview,textbox,windows-forms-designer,C#,Sql,Datagridview,Textbox,Windows Forms Designer,我正在尝试创建一个数据库读取器。在这里,我在文本框中添加要在db中运行的查询,然后单击按钮并在datagridview中获得结果 public partial class Form1 : Form { SqlCommand cmd = new SqlCommand(); SqlDataReader rdr; DataSet ds; SqlDataAdapter da; public Form1() { InitializeComp

我正在尝试创建一个数据库读取器。在这里,我在文本框中添加要在db中运行的查询,然后单击按钮并在datagridview中获得结果

public partial class Form1 : Form
{
    SqlCommand cmd = new SqlCommand();
    SqlDataReader rdr;
    DataSet ds;
    SqlDataAdapter da;

    public Form1()
    {
        InitializeComponent();
    }

    private void btnEnter_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=Apples;Initial Catalog=Abpee;Integrated Security=True;user id=sash;password=12345");
        con.Open();
        cmd.CommandText = txtSqlString.Text.Trim();
        cmd.Connection = con;
        rdr = cmd.ExecuteReader();
        bool temp = false;
        while (rdr.Read())
        {
            txtSqlString.Text = Convert.ToString(rdr[0].ToString());
            temp = true;
        }
        if (temp == false)
            MessageBox.Show("not found");
        con.Close();

        con.Open();
        ds = new DataSet();
        da = new SqlDataAdapter(" ", con);
        da.Fill(ds);
        con.Close();
        dgvResult.ReadOnly = true;
        dgvResult.DataSource = ds.Tables;
    }
}

您没有为
SqlDataAdapter
设置任何sql命令,也没有正确设置数据源

    da = new SqlDataAdapter(txtSqlString.Text.Trim(), con);
    da.Fill(ds);
    con.Close();
    dgvResult.ReadOnly = true;
    dgvResult.DataSource = ds.Tables[0];

另外,至少用
try.将其包装起来。。捕捉
,在失败时通知用户。我应该说这是相当危险的代码

而且。。。问题是什么?@TheGeneral sql连接很好,我认为它确实运行了我在文本框中添加的查询,但没有正确运行,然后没有在datagridview中显示结果