在页面加载时,显示复选框选中或未选中 [英] Upon Pageload, Show Checkbox Checked Or Unchecked

查看:301
本文介绍了在页面加载时,显示复选框选中或未选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在复选框的gridview中有一列。我希望能够根据数据库中相应的值来显示这些框(可以选中或不选中)(当前这个列没有绑定到任何字段,我遇到了问题)。一直给我带来问题的事情是我正在使用Ajax。当我执行AutoPostBack = true时,复选框只出现一次,然后当它刷新所有内容时,检查消失。任何帮助将不胜感激。

.CS

 公共部分类vieworders:System.Web.UI.Page 
{
private string orderByString;
private string fieldString;
私有字符串地址;
private DataGrid dataGrid = new DataGrid();


protected void Page_Load(object sender,EventArgs e)
{

orderByString = orderByList.SelectedItem.Value;
fieldString = searchTextBox.Text;
string sqlStatement =SELECT fName,lName,zip,email,cwaSource,price,length FROM SecureOrders WHERE fName LIKE'%+ fieldString +%或lName LIKE'%+ fieldString +%OR zip LIKE'%'+ fieldString +%或zip zip LIKE'%+ fieldString +%OR email LIKE'%+ fieldString +%或cwaSource LIKE'%+ fieldString +%OR length LIKE' %+ fieldString +%或价格LIKE'%+ fieldString +%'ORDER BY+ orderByString;
////////////////////////////


System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager。
OpenWebConfiguration(/ Cabot3);
System.Configuration.ConnectionStringSettings connectionString;

connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings [secureodb];

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



//创建一个到数据库的SqlConnection。
using(SqlConnection connection = new SqlConnection(connectionString.ToString()))
{
connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlStatement,connection);


//创建一个SqlCommandBuilder - 这将自动生成
//命令,并在dataAdapter中设置适当的属性
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter );

//创建DataSet
DataSet dataSet = new DataSet();
//使用DataAdapter填充DataSet
$ b $ dataAdapter.Fill(dataSet,SecureOrders);


SqlCommand cmd = new SqlCommand(SELECT * FROM SecureOrders,connection); //可能不需要这个
SqlCommand bitCmd = new SqlCommand(Select IsNull(processed,0)as processedField From SecureOrders,connection);
DataView source = new DataView(dataSet.Tables [0]);
DefaultGrid.DataSource = source;
DefaultGrid.DataBind();




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

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

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

OrderBrowser.Text =姓名+电子邮件+长度+价格+来源;
}

保护无效CheckBoxProcess_CheckedChanged(object sender,EventArgs e)
{
CheckBox cb =(CheckBox)sender;
GridViewRow gr =(GridViewRow)cb.NamingContainer;
if(cb.Checked)
{
OrderBrowser.Text =checked;
}
else
{
OrderBrowser.Text =unchecked;
}

}

}

.aspx

 <%@ Page Language =C#AutoEventWireup =trueCodeBehind =vieworders.aspx。 csInherits =Cabot3.custserv.vieworders%> 



  < asp:DropDownList runat =serverID =orderByListAutoPostBack =true> 
< asp:ListItem Value =fNameSelected =True>名字< / asp:ListItem>
< asp:ListItem Value =lName>姓氏< / asp:ListItem>
< asp:ListItem Value =state>状态< / asp:ListItem>
< asp:ListItem Value =zip>邮政编码< / asp:ListItem>
< asp:ListItem Value =cwaSource>源< / asp:ListItem>
< asp:ListItem Value =cwaJoined>加入日期< / asp:ListItem>
< / asp:DropDownList>
< / div>
< div>
< asp:Label runat =serverID =searchLabelText =Search For:/>
< asp:TextBox ID =searchTextBoxrunat =serverColumns =30/>
< asp:Button ID =searchButtonrunat =serverText =Search/>
< / div>
< div>
< asp:UpdatePanel ID =uprunat =server>



< ContentTemplate>
< div style =overflow:auto; height:150px; width:700px> b
onselectedindexchanged =DefaultGrid_SelectedIndexChanged
autogenerateselectbutton =true
的selectedIndex = 0 >
< SelectedRowStyle BackColor =Azure
forecolor =Black
font-bold =true/>
<列>
< asp:TemplateField HeaderText =Processed>
< ItemTemplate>
< asp:CheckBox ID =CheckBoxProcessOnCheckedChanged =CheckBoxProcess_CheckedChangedrunat =serverEnabled =true/>
< / ItemTemplate>
< / asp:TemplateField>
< /列>
< / asp:GridView>
< / div>
< / div>
< asp:TextBox ID =OrderBrowsercolumns =70Rows =14runat =serverWrap =falseTextMode =MultiLineReadOnly =true/>
< / ContentTemplate>
< / asp:UpdatePanel>



< / div>
< / form>




解决方案

因为当你点击复选框时,在AJAX回推期间, page_load 事件在 CheckBoxProcess_CheckedChanged 你的Gridview被再次绑定。



它应该是...

  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 +%或lName LIKE'%+ fieldString +%OR zip LIKE'%'+ fieldString +%或zip zip LIKE'%+ fieldString +%OR email LIKE'%+ fieldString +%或cwaSource LIKE'%+ fieldString +%OR length LIKE' %+ fieldString +%或价格LIKE'%+ fieldString +%'ORDER BY+ orderByString;
////////////////////////////


System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager。
OpenWebConfiguration(/ Cabot3);
System.Configuration.ConnectionStringSettings connectionString;

connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings [secureodb];

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



//创建一个到数据库的SqlConnection。
using(SqlConnection connection = new SqlConnection(connectionString.ToString()))
{
connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlStatement,connection);


//创建一个SqlCommandBuilder - 这将自动生成
//命令,并在dataAdapter中设置适当的属性
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter );

//创建DataSet
DataSet dataSet = new DataSet();
//使用DataAdapter填充DataSet
$ b $ dataAdapter.Fill(dataSet,SecureOrders);


SqlCommand cmd = new SqlCommand(SELECT * FROM SecureOrders,connection); //可能不需要这个
SqlCommand bitCmd = new SqlCommand(Select IsNull(processed,0)as processedField From SecureOrders,connection);
DataView source = new DataView(dataSet.Tables [0]);
DefaultGrid.DataSource = source;
DefaultGrid.DataBind();
}
}

编辑:你的评论,你不需要迭代gridiew行来设置复选框状态。您可以使用GridView的RowDataBound事件,也可以直接绑定该值。例如

 < asp:CheckBox ID =CheckBoxProcessChecked ='<%#Eval(processedField)%> ;'OnCheckedChanged =CheckBoxProcess_CheckedChangedrunat =serverEnabled =true/> 

更新:请更改以下代码

  //创建一个到数据库的SqlConnection。 
using(SqlConnection connection = new SqlConnection(connectionString.ToString()))
{
connection.Open();

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

//创建DataSet
DataSet dataSet = new DataSet();
//使用DataAdapter填充DataSet
dataAdapter.Fill(dataSet,SecureOrders);

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


I have a column in a gridview of checkboxes. I want to be able to display those boxes to be either checked or unchecked according to the corresponding value in the database (currently this column is not bound to any field, I'm having problems with that). Something that has been giving me problems is the fact that I'm using Ajax. when I do AutoPostBack = true, the checkbox appears checked for only a moment, and then when it refreshes everything the check disappears. Any help would be appreciated.

.CS

public partial class vieworders : System.Web.UI.Page
{
    private string orderByString;
    private string fieldString;
    private string address;
    private DataGrid dataGrid = new DataGrid();


    protected void Page_Load(object sender, EventArgs e)
    {

         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;
            ////////////////////////////


            System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.
                OpenWebConfiguration("/Cabot3");
            System.Configuration.ConnectionStringSettings connectionString;

            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.
            using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
            {
                connection.Open();
                SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlStatement, connection);


                // create an SqlCommandBuilder - this will automatically generate the
                // commands, and set the appropriate properties in the dataAdapter
                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

                // create the DataSet
                DataSet dataSet = new DataSet();
                // fill the DataSet using our DataAdapter

                dataAdapter.Fill(dataSet, "SecureOrders");


                SqlCommand cmd = new SqlCommand("SELECT * FROM SecureOrders", connection);  // might not need this
                SqlCommand bitCmd = new SqlCommand("Select IsNull(processed,0) as processedField From SecureOrders", connection);
                DataView source = new DataView(dataSet.Tables[0]);
                DefaultGrid.DataSource = source;
                DefaultGrid.DataBind();
            }


         }

    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;
        if (cb.Checked)
        {
            OrderBrowser.Text = "checked";
        }
        else
        {
            OrderBrowser.Text = "unchecked";
        }

    }

    }

.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" 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>

解决方案

Its because when you click on the checkbox, During the AJAX postaback, your page_load event fires before CheckBoxProcess_CheckedChanged where your Gridview is binded again.

It should be like...

If(!IsPostBack)  // you missed this condition
{
   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;
        ////////////////////////////


        System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.
            OpenWebConfiguration("/Cabot3");
        System.Configuration.ConnectionStringSettings connectionString;

        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.
        using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
        {
            connection.Open();
            SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlStatement, connection);


            // create an SqlCommandBuilder - this will automatically generate the
            // commands, and set the appropriate properties in the dataAdapter
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

            // create the DataSet
            DataSet dataSet = new DataSet();
            // fill the DataSet using our DataAdapter

            dataAdapter.Fill(dataSet, "SecureOrders");


            SqlCommand cmd = new SqlCommand("SELECT * FROM SecureOrders", connection);  // might not need this
            SqlCommand bitCmd = new SqlCommand("Select IsNull(processed,0) as processedField From SecureOrders", connection);
            DataView source = new DataView(dataSet.Tables[0]);
            DefaultGrid.DataSource = source;
            DefaultGrid.DataBind();
        }
}

Edit: After following your comments, you don't need to iterate the gridiew rows to set the checkbox state. You can either use the RowDataBound event of GridView or directly bind the value. e.g.

<asp:CheckBox ID="CheckBoxProcess" Checked='<%#Eval("processedField") %>' OnCheckedChanged="CheckBoxProcess_CheckedChanged"  runat="server" Enabled="true" />

Update: Please change the following code with this one

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

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

            // create the DataSet
            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();
        }

这篇关于在页面加载时,显示复选框选中或未选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆