SQL Server:Datagridview显示表中的列值

时间:2013-09-05 04:39:10

标签: c# sql sql-server datagridview

我想在datagridview中显示指定的列值。示例:来自表格user_account我希望在datagridview

中按列account的文本框数据进行显示和搜索

以下是目前的代码:

private void button3_Click(object sender, EventArgs e)
{
        string connectionString = @"Data Source=" + textBox4.Text + ";" + "Initial Catalog=" + textBox1.Text + ";" + "User ID=" + textBox2.Text + ";" + "Password=" + textBox3.Text;
        string sql = "SELECT * FROM user_account";
        SqlConnection connection = new SqlConnection(connectionString) ;
        SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
        DataSet ds = new DataSet();
        connection.Open();
        dataadapter.Fill(ds, "account");
        connection.Close();
        dataGridView1.DataSource = ds;
        dataGridView1.DataMember = "account";
    }

2 个答案:

答案 0 :(得分:1)

private void button3_Click(object sender, EventArgs e)
    {
        string connectionString = @"Data Source=" + textBox4.Text + ";" + "Initial Catalog=" + textBox1.Text + ";" + "User ID=" + textBox2.Text + ";" + "Password=" + textBox3.Text;
        string sql = "SELECT account FROM user_account";
        SqlConnection connection = new SqlConnection(connectionString) ;
        SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
        DataSet ds = new DataSet();
        connection.Open();
        dataadapter.Fill(ds, "account");
        connection.Close();
        dataGridView1.DataSource = ds;

    }

答案 1 :(得分:0)

解决方案:

        private void button3_Click(object sender, EventArgs e)
    {
        string connectionString = @"Data Source=" + textBox4.Text + ";" + "Initial Catalog=" + "lin2db" + ";" + "User ID=" + textBox2.Text + ";" + "Password=" + textBox3.Text;
        string sql = "SELECT account ,pay_stat FROM user_account where account='" + textBox7.Text + "' ";          
        SqlConnection connection = new SqlConnection(connectionString) ;
        SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
        DataSet ds = new DataSet();
        connection.Open();
        dataadapter.Fill(ds, "pay_stat");
        connection.Close();
        dataGridView1.DataSource = ds;
        dataGridView1.DataMember = "pay_stat";


    }

感谢您的帮助。