有人可以帮我修改这段代码,让它在 C# ASP.NET 中工作吗?

时间:2021-05-24 04:17:19

标签: c# sql asp.net asp.net-web-api

用户应该能够在表单顶部的文本框中输入学号,并且所有信息都应该以网格视图顺序显示。 用户应该能够点击“归还图书”按钮归还图书

注意:我没有连接到我的数据库,有人可以更正此代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;

namespace CHS_Online_Library.Admin 
{
  public partial class ReturnBooks: System.Web.UI.Page 
  {
    string str = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
    
    protected void Page_Load(object sender, EventArgs e) 
    {
      dataGridView1_bookreturn.DataSource = GetBookReturnList();
    }

    private DataTable GetBookReturnList() 
    {
      DataTable dtViewBook = new DataTable();

      using(SqlConnection con = new SqlConnection(str)) 
      {
        using(SqlCommand cmd = new SqlCommand("SELECT * FROM BookReturn", con)) 
        {
          con.Open();
          SqlDataReader reader = cmd.ExecuteReader();

          dtViewBook.Load(reader);
        }
      }

      return dtViewBook;
    }

    protected void BR_Return_Click(object sender, EventArgs e) 
    {
      SqlConnection con = new SqlConnection();
      con.ConnectionString = "";
      SqlCommand cmd = new SqlCommand();
      cmd.Connection = con;

      try 
      {
        con.Open();
        cmd.CommandText = "insert into BookReturn(StudentID, BookName,IssueDate,ReturnDate,) values('" + textBox_brsearch.Text + "', '" + BR_bookname.Text + "', '" + BR_issuedate.Text + "', '" + dateTimePicker1.Text + "')";
        cmd.ExecuteNonQuery();
        lblRMsg.Text = "Book was return successfully";
        lblRMsg.Visible = true;
        lblRMsg.ForeColor = Color.Green;

      } catch (Exception ex) {
        lblRMsg.Text = "Try Again";
        lblRMsg.Visible = true;
        lblRMsg.ForeColor = Color.Red;

      } finally {
        con.Close();
      }
    }

    protected void textBox_brsearch_TextChanged(object sender, EventArgs e) 
    {
      {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "";
        con.Open();
        if (textBox_brsearch.Text != "") 
        {
          SqlCommand cmd = new SqlCommand("Select BookName, IssueDate from IssueBook where StudentID =@StudentID", con);
          cmd.Parameters.AddWithValue("@StudentID", int.Parse(textBox_brsearch.Text));
          SqlDataReader da = cmd.ExecuteReader();
          while (da.Read()) {
            BR_bookname.Text = da.GetValue(0).ToString();
            BR_issuedate.Text = da.GetValue(1).ToString();

          }
          con.Close();
        }
      }

    }
  }
}

1 个答案:

答案 0 :(得分:0)

我不知道我是否正确,但是查看您的代码以及您的解释,我认为就是这样。

protected void Page_Load(object sender, EventArgs e) 
{
    dataGridView1_bookreturn.DataSource = GetBookReturnList();
    dataGridView1_bookreturn.DataBind(); //you forget this part
}

参见reference