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

Read sql string from textbox and display in datagridview

我正在尝试创建数据库 reader。我在文本框中的数据库中添加我想要 运行 的查询,然后单击按钮并在 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 命令,也没有正确设置 DataSource。

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

加上至少用 try .. catch 包装起来,以便在失败时通知用户。我应该说这是相当危险的代码。