根据C#中的数据表填充表单值

时间:2014-02-15 19:19:43

标签: c# .net winforms sqlite datatable

我正在返回一行数据表,然后我设置数据表的主键,然后查找该列。然后,我想将company列返回的值分配到txtCompany

以下是我的尝试:

private void comboBox1_SelectedItem(object sender, EventArgs e)
{
    MessageBox.Show("Populating form");
    m_dbConnection.Open();

    DataTable dt = new DataTable();
    SQLiteCommand command = m_dbConnection.CreateCommand();
    command.CommandText = "select * from rdpdirectory where company = @company order by company asc";
    //
    command.Parameters.Add(new SQLiteParameter("@company", comboBox1.SelectedText));
    SQLiteDataAdapter db = new SQLiteDataAdapter(command);
    db.Fill(dt);
    //return dt;

    DataColumn[] keyColumns = new DataColumn[1];
    keyColumns[0] = dt.Columns["company"];
    dt.PrimaryKey = keyColumns;

    DataRow row = dt.Rows.Find("company");
    if (row != null)
        txtCompany.Text = row["company"].ToString();
}   

1 个答案:

答案 0 :(得分:-1)

我用以下代码解决了它:

private void comboBox1_SelectedItem(object sender, EventArgs e)
        {
            MessageBox.Show("Populating form");
            m_dbConnection.Open();

            DataTable dt = new DataTable();
            SQLiteCommand command = m_dbConnection.CreateCommand();
            command.CommandText = "select * from rdpdirectory where company = @company order by company asc";
            //
            command.Parameters.Add(new SQLiteParameter("@company", comboBox1.SelectedText));
            SQLiteDataAdapter db = new SQLiteDataAdapter(command);
            db.Fill(dt);
            //return dt;


            DataColumn[] keyColumns = new DataColumn[1];
            keyColumns[0] = dt.Columns["company"];
            dt.PrimaryKey = keyColumns;

            DataRow row = dt.Rows[0];
            txtCompany.Text = row["company"].ToString();
            txtServer.Text = row["server"].ToString();
            txtUserName.Text = row["username"].ToString();
            txtPassword.Text = row["password"].ToString();
        }