【问题标题】:Read sql string from textbox and display in datagridview从文本框中读取 sql 字符串并在 datagridview 中显示
【发布时间】:2019-07-16 07:22:12
【问题描述】:

我正在尝试创建一个数据库阅读器。我在文本框中添加要在数据库中运行的查询,然后单击按钮并在 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;
    }
}

【问题讨论】:

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

标签: c# sql datagridview textbox windows-forms-designer


【解决方案1】:

你没有为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 包装它,以便在失败时通知用户。我应该说这是相当危险的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    相关资源
    最近更新 更多