【问题标题】:C# - Selecting SQL Table contents into textboxC# - 将 SQL 表内容选择到文本框中
【发布时间】:2016-10-06 04:39:31
【问题描述】:

当 button_click 事件发生时,尝试通过首选 ID 号将表格内容分别放入文本框。我发现了一些关于这种情况的视频,但其中使用了 dataGrids。顺便说一句,我是 C# 的新手,我什至不确定自己在做什么。

问题是,我不知道如何将下面在代码中说明的只读对象写入文本框。我 %90 确定这确实是一件简单的事情,但我很想念它。

private void button2_Click(object sender, EventArgs e)
{
    SqlCommand rcmd = new SqlCommand("SELECT ID, Column1, Column2 FROM [TEST].[dbo].[Table_1] where ID=@ID", connection);
    rcmd.Parameters.AddWithValue("@ID", textBox3.Text);
    connection.Open();
    SqlDataReader reader = rcmd.ExecuteReader();

    while (reader.Read())
    {
        //textBox4.Text = reader["Column1"];
        //textBox5.Text = reader["Column2"];
        //These wont work, says reader["Column1"] and reader["Column2"] are read-only. What to do?
    }
    connection.Close();

有意注释错误的行。那里没有错。我试图在保持视线的同时想出别的东西。

提前致谢。

【问题讨论】:

  • 我认为您应该做相反的事情... textBox4.Text = reader["Column1"],因为您将文本框的值设置为阅读器的值。
  • @Alex 是的,你通常会那样做。但还是不行。 :L 表示不能将对象隐式更改为字符串。等一下。我想我得到了一些见解。
  • @Alex 你这样做会发生什么?有什么错误吗?
  • 刚刚编辑了评论。
  • textBox4.Text = reader["Column1"].ToString() ?

标签: c# sql select


【解决方案1】:
reader["Column1"].ToString();

你错过了ToString()

【讨论】:

  • 谢谢你:)
  • 老兄,帮自己一个忙,拿起一本初学者的C#书
  • 再次感谢您的关注。
【解决方案2】:
    private void button2_Click(object sender, EventArgs e)
        {
            SqlCommand rcmd = new SqlCommand("SELECT ID, Column1, Column2 FROM [TEST].[dbo].[Table_1] where ID=@ID", connection);

            rcmd.Parameters.AddWithValue("@ID", textBox3.Text);
            connection.Open();
            SqlDataReader reader = rcmd.ExecuteReader();


            while (reader.Read())
            {

                textBox4.Text = reader["Column1"].ToString();
                textBox5.Text = reader["Column2"].ToString();

            }
            connection.Close();
       }

【讨论】:

    猜你喜欢
    • 2014-07-29
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多