【问题标题】:Connect dataGridView to SQL query将 dataGridView 连接到 SQL 查询
【发布时间】:2018-05-05 20:30:55
【问题描述】:

我正在使用 C# Windows Forms 和 SQL 数据库构建一个简单的预订系统。作为程序的一部分,用户可以向文本框添加一些文本并单击“搜索”按钮来搜索符合搜索条件的预订。 当用户点击按钮时,执行SQL查询,查询结果更新到dataGridView中。

下面的示例是我的代码中的简单示例。 booking_id 的格式是 int 和 firstname 的字符串。程序不断抛出System.InvalidCastException,并且错误与试图将booking_id 插入SQL 字符串的行有关。我已经搜索了有关此错误的一些信息,但我仍然无法修复它。我在这里想念的东西一定很简单-有人可以提供帮助吗?提前谢谢你!

// User clicks 'Search' butto.
private void button_Search1_Click(object sender, EventArgs e)
{
    string commandText = "SELECT * FROM Booking " +
        "INNER JOIN Customer ON Booking.customer_id = Customer.customer_id" +
        "WHERE Booking.booking_date IS NOT NULL AND " +
        "Booking.booking_id_id LIKE '%' + @booking_id + '%' " +
        "Customer.customer.firstname LIKE '%' + @firstname + '%'";

    using (SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;" + @"AttachDbFilename=|DataDirectory|\Booking.mdf; Integrated Security=True"))
    {
        //Create a SqlCommand instance
        SqlCommand command = new SqlCommand(commandText, connection);

        //Add the parameter
        //THESE LINES CAUSE PROBLEM!?
        command.Parameters.Add("@booking_id", SqlDbType.Int).Value = Convert.ToInt32(textBox_BookindId);
        command.Parameters.Add("@firstname", SqlDbType.VarChar, 20).Value = textBox_Firstname;

        // Open SQL connection and execute query.
        connection.Open();
        command.ExecuteNonQuery();

        SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
        DataTable dt = new DataTable();
        dataAdapter.Fill(dt);
        dataGridView1.DataSource = dt;

【问题讨论】:

  • 阅读整个异常消息。我敢打赌它说的是这样的:“附加信息:无法将'System.Windows.Forms.TextBox'类型的对象转换为'System.IConvertible'类型。”

标签: c# sql winforms datagridview


【解决方案1】:

如果目标是强制Datatable dt 中的booking_id_id 列成为一个字符串,以便它很好地进入文本框,那么CAST 预订ID 在被选中时成为一个字符串。请注意,我使用 'as' 将列命名为 Booking ID

string commandText = "SELECT Customer.customer_id, Booking.booking_date, CAST(Booking.booking_id_id) as NVARCHAR(10)) as 'Booking ID', Customer.customer.firstname FROM Booking " + "INNER JOIN Customer ON Booking.customer_id = Customer.customer_id" + "WHERE Booking.booking_date IS NOT NULL AND " + "Booking.booking_id_id LIKE '%' + @booking_id + '%' " + "Customer.customer.firstname LIKE '%' + @firstname + '%'";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    相关资源
    最近更新 更多