在按钮单击时从表中选择数据

时间:2017-04-03 20:18:19

标签: c# sql datagridview

我正在尝试将表提取到DataGridView,但它显示了一个空表。

private void button1_Click(object sender, EventArgs e)
{
    var dt = new DataTable();

    var SDA = new SqlDataAdapter("Select * from "+txt_Search.Text+" ", conn);

    SDA.Fill(dt);
    dgv.DataSource = dt;
    txt_Search.Text = "";
}

1 个答案:

答案 0 :(得分:0)

您提供的代码段没有提供太多上下文。请尝试使用我提供的以下代码段。也许你看到了你错过的东西。希望这会有所帮助。

const string connectionString = "";
SqlConnection connection = new SqlConnection(connectionString)

public DataTable ExecuteCommandToDataTable(string commandText, CommandType 
commandType, int timeout, params SqlParameter[] parameters)
{
    if (this.connection == null)
        throw new NullReferenceException("The connection was not initialized.");

    SqlCommand command = new SqlCommand(commandText, 
    this.connection.SqlConnection);            
    command.CommandType = commandType;
    command.CommandTimeout = timeout;

    for (int i = 0; parameters != null && i < parameters.Length; i++)
        command.Parameters.Add(parameters[i]);


    this.connection.Open();

    DataTable tbl = new DataTable();
    using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand))
    {
        adapter.Fill(tbl);
    }

    this.connection.Close();

    return tbl;
}