【问题标题】:Update database bit value更新数据库位值
【发布时间】:2011-07-11 18:13:24
【问题描述】:

我正在尝试在检查或未选中复选框时写入数据库。如果复选框被选中,我们希望能够存储 1(位值),如果未选中,则存储 0。这样,如果它已被选中,当表单加载时,我们将在复选框中看到一个选中状态。否则,一个也没有。这是我目前所拥有的:

C#
    public partial class vieworders : System.Web.UI.Page
{
    private string orderByString;
    private string fieldString;
    private string address;
    private DataGrid dataGrid = new DataGrid();
    SqlDataAdapter dataAdapter;
    DataSet dataSet;


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            orderByString = orderByList.SelectedItem.Value;
            fieldString = searchTextBox.Text;
            string sqlStatement = "SELECT fName,lName,zip,email,cwaSource,price,length FROM SecureOrders WHERE fName LIKE '%" + fieldString + "%' OR lName LIKE'%" + fieldString + "%'  OR zip LIKE'%" + fieldString + "%' OR zip LIKE'%" + fieldString + "%'  OR email LIKE'%" + fieldString + "%' OR cwaSource LIKE'%" + fieldString + "%' OR length LIKE'%" + fieldString + "%' OR price LIKE'%" + fieldString + "%' ORDER BY " + orderByString;
            ////////////////////////////




            connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["secureodb"];

            //TEST
            for (int i = 0; i < DefaultGrid.Rows.Count; i++)
            {
                CheckBox chkUpdate = (CheckBox)DefaultGrid.Rows[i].Cells[1].FindControl("CheckBoxProcess");
                if (chkUpdate != null)
                {
                    OrderBrowser.Text += "Test";
                }
            }



            // Create an SqlConnection to the database.
            // Create an SqlConnection to the database.
            using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
            {
                connection.Open();

                dataAdapter = new SqlDataAdapter("SELECT * FROM SecureOrders", connection);

                // create the DataSet
                dataSet = new DataSet();
                // fill the DataSet using our DataAdapter               
                dataAdapter.Fill(dataSet, "SecureOrders");

                DataView source = new DataView(dataSet.Tables[0]);
                DefaultGrid.DataSource = source;
                DefaultGrid.DataBind();
                connection.Close();
            }
        }


         }




    protected void DefaultGrid_SelectedIndexChanged(Object sender, EventArgs e)
    {
        GridViewRow row = DefaultGrid.SelectedRow;
        string name = "Name: " + row.Cells[2].Text + " " + row.Cells[3].Text + "\r\n";
       // if (row.Cells[4].Text == "&nbsp;")
        //{
            //address = "Address: " + row.Cells[3].Text + "\r\n         " + row.Cells[5].Text + ", " + row.Cells[6].Text + " " + row.Cells[7].Text + " " + row.Cells[8].Text + "\r\n";

       // }
        //else
       // {
           // address = "Address: " + row.Cells[3].Text + "\r\n         " + row.Cells[4].Text + "\r\n         " + row.Cells[5].Text + ", " + row.Cells[6].Text + " " + row.Cells[7].Text + " " + row.Cells[8].Text + "\r\n";
        //}

        string zip = "Zip: " + row.Cells[4].Text + "\r\n";
        string email = "Email: " + row.Cells[5].Text + "\r\n";
        //string phone = "Phone: " + row.Cells[10].Text + "\r\n";
        //string cctype = "Credit Card Type: " + row.Cells[11].Text + "\r\n";
        //string ccnum = "Credit Card Number: " + row.Cells[12].Text + "\r\n";
        //string ccexp = "Credit Card Expiration: " + row.Cells[13].Text + "\r\n";
        string length = "Length: " + row.Cells[8].Text + "\r\n";
        //string delivery = "Delivery: " + row.Cells[15].Text + "\r\n";
        string price = "Price: " + row.Cells[7].Text + "\r\n";
        string source = "Source: " + row.Cells[6].Text + "\r\n";
        //string joined = "Joined: " + row.Cells[18].Text + "\r\n";
        //string url = "URL: " + row.Cells[19].Text + "\r\n";

        OrderBrowser.Text = name + email + length + price + source;
    }

    protected void CheckBoxProcess_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox cb = (CheckBox)sender;
        GridViewRow gr = (GridViewRow)cb.NamingContainer;




        connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["secureodb"];

        using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
        {
            connection.Open();


            dataAdapter = new SqlDataAdapter("SELECT * FROM SecureOrders", connection);

            // create the DataSet
            dataSet = new DataSet();
            // fill the DataSet using our DataAdapter               
            dataAdapter.Fill(dataSet, "SecureOrders");
            DataSet myDSchanged = dataSet.GetChanges(DataRowState.Modified);
            SqlCommandBuilder builder = new SqlCommandBuilder(dataAdapter);

            dataAdapter.Update(myDSchanged, "SecureOrders");
            dataSet.AcceptChanges();
            connection.Close();
        }




    }

    }

aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="vieworders.aspx.cs" Inherits="Cabot3.custserv.vieworders" %>

        <asp:DropDownList runat="server" ID="orderByList" AutoPostBack="true">
            <asp:ListItem Value="fName" Selected="True">First Name</asp:ListItem>
            <asp:ListItem Value="lName">Last Name</asp:ListItem>
            <asp:ListItem Value="state">State</asp:ListItem>
            <asp:ListItem Value="zip">Zip Code</asp:ListItem>
            <asp:ListItem Value="cwaSource">Source</asp:ListItem>
            <asp:ListItem Value="cwaJoined">Date Joined</asp:ListItem>
        </asp:DropDownList>
    </div>
    <div>
        <asp:Label runat="server" ID="searchLabel" Text="Search For: " />
        <asp:TextBox ID="searchTextBox" runat="server" Columns="30" />
        <asp:Button ID="searchButton" runat="server" Text="Search" />
    </div>
<div>
<asp:UpdatePanel ID = "up" runat="server">



    <ContentTemplate>
    <div style= "overflow:auto; height:150px; width:700px">
    <asp:GridView ID="DefaultGrid" runat = "server"  DataKeyNames = "fName, lName, zip"
    onselectedindexchanged = "DefaultGrid_SelectedIndexChanged"
    autogenerateselectbutton = "true"
    selectedindex="0">
    <SelectedRowStyle BackColor="Azure"
    forecolor="Black"
    font-bold="true" />
    <Columns>
    <asp:TemplateField HeaderText="Processed">
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBoxProcess" AutoPostBack = "true" Checked ='<%#Eval("processed") %>' OnCheckedChanged="CheckBoxProcess_CheckedChanged"  runat="server" Enabled="true" />
                </ItemTemplate>
            </asp:TemplateField>
    </Columns>
    </asp:GridView>
    </div>
    </div>
    <asp:TextBox ID="OrderBrowser" columns="70" Rows="14" runat="server" Wrap="false" TextMode="MultiLine" ReadOnly = "true"/>
    </ContentTemplate>
    </asp:UpdatePanel>



</div>
</form>

谁能引导我朝正确的方向前进?

【问题讨论】:

  • 不,不是!为什么,我做的事情完全错了吗?
  • 当我说“我们”时,我指的是我的公司。
  • 哪些部分有效,哪些无效?我看不到您的网格列与您的 dataAdapter 绑定的位置。
  • 好的,我已经添加了我所有的代码。基本上,数据库不会在复选框的 checkedchanged 事件时更新。我希望它在用户单击复选框时更改数据库中的“已处理”字段。
  • 您甚至没有尝试更新 CheckBoxProcess_CheckedChanged 中的任何数据库值。

标签: c# asp.net sql ado.net


【解决方案1】:

这是我为您编写的一个静态方法作为辅助方法。它采用布尔值,并在列中设置 0 或 1 位值。你当然需要用你的表名、列名等来修改它。我刚刚创建了一个简单的测试数据库来向你展示如何做到这一点。

现在,这假定该行已经存在于数据库中。在我的测试数据库中,我的表名为“设置”,并包含三列:

  • ID(整数)
  • 名称 (nvarchar(50))
  • 值 (nvarchar(50))

已经存在 ID 为 0、名称为“CheckboxState”且值为 0 的行。因此,最初您应该有某种机制,首先将该行放入数据库中。

但是,本质上,您可以在代码隐藏中调用它,并将 CheckBox.Checked 属性传递给它。

static void UpdateCheckedState(bool state) {
    string connectionstring = "<yourconnectionstring>";
    using (SqlConnection connection = new SqlConnection(connectionstring)) {
        try {
            connection.Open();
        }
        catch (System.Data.SqlClient.SqlException ex) {
            // Handle exception
        }
        string updateCommandText = "UPDATE Settings SET Value = @state WHERE Name = 'CheckboxState'";
        using (SqlCommand updateCommand = new SqlCommand(updateCommandText, connection)) {
            SqlParameter stateParameter = new SqlParameter("state", state);
            updateCommand.Parameters.Add(stateParameter);
            try {
                updateCommand.ExecuteNonQuery();
            }
            catch (System.Data.SqlClient.SqlException ex) {
                // Handle exception
            }
        }
    }
}

【讨论】:

  • 谢谢 - 我要试试这个。数据库中的字段是“已处理”,列 ID 是“CheckBoxProcess”,它们都是初始检查的,因此值为 1!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
  • 1970-01-01
  • 2010-12-27
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 1970-01-01
相关资源
最近更新 更多