SQL Server 中的 C# CheckBoxList 更新

发布于 2024-11-24 15:45:27 字数 3532 浏览 7 评论 0原文

请检查下面的 C# 代码并让我知道哪里出了问题。以下是我遇到的情况:

1.) 如果我清空 SQL Server 中的 SendReport 列并加载页面,SendReport 的第二行会自动填充 1 2.

) 我可以打勾,单击按钮,SendReport 值会成功填充到 SQL Server 中。但是,如果我取消选中其中任何一个并单击按钮,则所有值都不会从 1 更改为 0。请帮忙!

$<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
<br />
<asp:Button ID="Button1" runat="server" Text="Save Changes" OnClick="Button1_Click" />
<br />


BACKPAGE:
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        BindCheckBoxList();
    }
}

//  Setting up the ConnectionString
public string GetConnectionString()
{
    return System.Configuration.ConfigurationManager.ConnectionStrings["IPdataConnectionString"].ConnectionString;
}

//  Binding the CheckBoxList with Data
private void BindCheckBoxList()
{
  DataTable dt = new DataTable();
  SqlConnection connection = new SqlConnection(GetConnectionString());
  try
  {
    connection.Open();
    string sqlStatement = "SELECT Partner, ID, SendReport FROM Rorts";
    SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

    sqlDa.Fill(dt);
    if (dt.Rows.Count > 0)
    {
      CheckBoxList1.DataSource = dt;
      CheckBoxList1.DataTextField = "Partner"; // the items to be displayed in the list items
      CheckBoxList1.DataValueField = "SendReport"; // the id of the items displayed
      CheckBoxList1.DataBind();

      //Setting the Selected Items in the ChecBoxList based from the value in the database
      //to do this, lets iterate to each items in the list
      for (int i = 0; i < dt.Rows.Count; i++)
      {
        if (!string.IsNullOrEmpty(dt.Rows[i]["SendReport"].ToString()))
        {
          CheckBoxList1.Items[i].Selected = Convert.ToBoolean(dt.Rows[i]["SendReport"]);
        }
      }
    }

  }
  catch (System.Data.SqlClient.SqlException ex)
  {
    string msg = "Fetch Error:";
    msg += ex.Message;
    throw new Exception(msg);
  }
  finally
  {
    connection.Close();
  }
}

//  Creating the Method for Saving the CheckBoxList Selected Items to the database
private void Update(string name, bool SendReport)
{
  SqlConnection connection = new SqlConnection(GetConnectionString());
  SqlCommand cmd;
  string sqlStatement = string.Empty;
    try
    {
      // open the Sql connection
      connection.Open();
      sqlStatement = "UPDATE Rorts SET SendReport = @SendReport WHERE Partner = @Partner";
      cmd = new SqlCommand(sqlStatement, connection);
      cmd.Parameters.AddWithValue("@Partner", name);
      cmd.Parameters.AddWithValue("@SendReport", SendReport);
      cmd.CommandType = CommandType.Text;
      cmd.ExecuteNonQuery();

    }
    catch (System.Data.SqlClient.SqlException ex)
    {
      string msg = "Insert/Update Error:";
      msg += ex.Message;
      throw new Exception(msg);
    }
    finally
    {
      // close the Sql Connection
      connection.Close();
    }
  }

//  Calling the Method for Saving the state of  CheckBoxList  selected items
protected void Button1_Click(object sender, EventArgs e)
{
    string PartnerName = string.Empty;

  for (int i = 0; i < CheckBoxList1.Items.Count; i++)
  {
    if (CheckBoxList1.Items[i].Selected)
    {
        PartnerName = CheckBoxList1.Items[i].Text;
        Update(PartnerName, CheckBoxList1.Items[i].Selected);
    }
  }
  //ReBind the List to retain the selected items on postbacks
  BindCheckBoxList();
}

Please inspect my C# code below and let me know where I am going wrong. Here is what I am experiencing:

1.) If I empty the SendReport column in SQL Server and load the page, the second row of the SendReport automatically gets populated with a 1.

2.) I can place a checkmark, click the button and the SendReport values successfully populate in SQL Server. However, if I uncheck any of them and click the button, none of the values change from 1 to 0. Please help!

lt;asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
<br />
<asp:Button ID="Button1" runat="server" Text="Save Changes" OnClick="Button1_Click" />
<br />


BACKPAGE:
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        BindCheckBoxList();
    }
}

//  Setting up the ConnectionString
public string GetConnectionString()
{
    return System.Configuration.ConfigurationManager.ConnectionStrings["IPdataConnectionString"].ConnectionString;
}

//  Binding the CheckBoxList with Data
private void BindCheckBoxList()
{
  DataTable dt = new DataTable();
  SqlConnection connection = new SqlConnection(GetConnectionString());
  try
  {
    connection.Open();
    string sqlStatement = "SELECT Partner, ID, SendReport FROM Rorts";
    SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

    sqlDa.Fill(dt);
    if (dt.Rows.Count > 0)
    {
      CheckBoxList1.DataSource = dt;
      CheckBoxList1.DataTextField = "Partner"; // the items to be displayed in the list items
      CheckBoxList1.DataValueField = "SendReport"; // the id of the items displayed
      CheckBoxList1.DataBind();

      //Setting the Selected Items in the ChecBoxList based from the value in the database
      //to do this, lets iterate to each items in the list
      for (int i = 0; i < dt.Rows.Count; i++)
      {
        if (!string.IsNullOrEmpty(dt.Rows[i]["SendReport"].ToString()))
        {
          CheckBoxList1.Items[i].Selected = Convert.ToBoolean(dt.Rows[i]["SendReport"]);
        }
      }
    }

  }
  catch (System.Data.SqlClient.SqlException ex)
  {
    string msg = "Fetch Error:";
    msg += ex.Message;
    throw new Exception(msg);
  }
  finally
  {
    connection.Close();
  }
}

//  Creating the Method for Saving the CheckBoxList Selected Items to the database
private void Update(string name, bool SendReport)
{
  SqlConnection connection = new SqlConnection(GetConnectionString());
  SqlCommand cmd;
  string sqlStatement = string.Empty;
    try
    {
      // open the Sql connection
      connection.Open();
      sqlStatement = "UPDATE Rorts SET SendReport = @SendReport WHERE Partner = @Partner";
      cmd = new SqlCommand(sqlStatement, connection);
      cmd.Parameters.AddWithValue("@Partner", name);
      cmd.Parameters.AddWithValue("@SendReport", SendReport);
      cmd.CommandType = CommandType.Text;
      cmd.ExecuteNonQuery();

    }
    catch (System.Data.SqlClient.SqlException ex)
    {
      string msg = "Insert/Update Error:";
      msg += ex.Message;
      throw new Exception(msg);
    }
    finally
    {
      // close the Sql Connection
      connection.Close();
    }
  }

//  Calling the Method for Saving the state of  CheckBoxList  selected items
protected void Button1_Click(object sender, EventArgs e)
{
    string PartnerName = string.Empty;

  for (int i = 0; i < CheckBoxList1.Items.Count; i++)
  {
    if (CheckBoxList1.Items[i].Selected)
    {
        PartnerName = CheckBoxList1.Items[i].Text;
        Update(PartnerName, CheckBoxList1.Items[i].Selected);
    }
  }
  //ReBind the List to retain the selected items on postbacks
  BindCheckBoxList();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘寄 2024-12-01 15:45:27

看起来问题是由于 Button1 单击事件处理程序中的 if 块引起的。结果是,只有选中的复选框才会将值保存到数据库中。

        if (CheckBoxList1.Items[i].Selected)
        {
            PartnerName = CheckBoxList1.Items[i].Text;
            Update(PartnerName, CheckBoxList1.Items[i].Selected);
        }

您可以删除 if 语句并保留所有值,或者添加逻辑以仅保留已更改的值。

It looks like the issue is due to the if block below from the Button1 click event handler. The result is that only the check boxes that are checked have the values persisted to the database.

        if (CheckBoxList1.Items[i].Selected)
        {
            PartnerName = CheckBoxList1.Items[i].Text;
            Update(PartnerName, CheckBoxList1.Items[i].Selected);
        }

You can just remove the if statement and persist all of the values or add logic to only persist those that have changed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文