【问题标题】:Database data into textbox数据库数据到文本框
【发布时间】:2017-05-13 11:28:23
【问题描述】:

有没有办法将数据库中的数据显示到文本框中,但是每次单击 NEXT 时都会显示新行。我有这段代码,但它不像我想要的那样工作,因为它将所有数据显示到一个文本框中,而不是一次显示一行。

private void buttonNEXT_Click(object sender, EventArgs e)
{
    SQLiteConnection conn = new SQLiteConnection("data source = people.sqlite");
    conn.Open();
    SQLiteCommand com = new SQLiteCommand(conn);
    com.CommandText = "SELECT id, name, surname FROM people;";
    SQLiteDataReader reader = com.ExecuteReader();
    while (reader.Read())
    {
        textBox1.Text += reader["id"].ToString(); 
        textBox2.Text += reader["name"].ToString();
        textBox3.Text += reader["surname"].ToString();
    }
    conn.Close();
}

【问题讨论】:

  • WinForms?您可能需要 BindingNavigator。但是,如果您只想转发访问,则可以使用 Reader - 只需在 click 事件之外执行您的阅读器并将其存储在变量中,然后在每次单击按钮时调用 Read,而不是“while(reader.Read())”

标签: c# database textbox


【解决方案1】:

如果您想要一个NextPrevious 按钮并且不想在您的表单上使用BindingNavigator 控件,您可以使用DataSet 来存储数据并使用SQLiteDataAdapter 来填充它。 所以你可以有一个函数来填充和返回一个数据集:

public DataSet GetDataSet(string ConnectionString, string SQL)
{
    SQLiteConnectionconn = new SQLiteConnection(ConnectionString);
    SQLiteDataAdapter da = new SQLiteDataAdapter ();
    SQLiteCommand cmd = conn.CreateCommand();
    cmd.CommandText = SQL;
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();

    conn.Open();
    da.Fill(ds);
    conn.Close();

    return ds;
}

那么你应该在你的主函数中将它的返回值保留为global variable,比如FormLoad

dataset ds; // global variable
int index = 0; // for loop over dataset
private void frm_Load(object sender, EventArgs e)
{
    ds = GetDataSet("data source = people.sqlite","SELECT id, name, surname FROM people;");
}

然后在您的按钮中单击:

private void buttonNEXT_Click(object sender, EventArgs e)
{
     textBox1.Text = ds.Tables["People"].Rows[i]["id"].ToString(); 
     textBox2.Text = ds.Tables["People"].Rows[i]["name"].ToString();
     textBox3.Text = ds.Tables["People"].Rows[i]["surname"].ToString();
     i++;
}

注意:你应该每次点击检查i变量值,它不能大于ds.Tables["People"].Rows.Count

如果你也想要上一个按钮,也可以这样做。

【讨论】:

  • 因为"+="你还有一半的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
  • 1970-01-01
  • 2011-07-26
相关资源
最近更新 更多