C# 如何通过单击按钮检查 gridview 列中复选框的状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/349087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 00:05:17  来源:igfitidea点击:

how to check status of checkboxes in gridview columns on click of button

c#asp.netjavascript

提问by Devashri B.

I have used checkbox column in gridview. I want to check status of that checkboxes. On click of a button it should be checked that if any checkbox is checked or not. If none checkbox is checked then it should display alert message that check checkbox first.

我在 gridview 中使用了复选框列。我想检查该复选框的状态。单击按钮时,应检查是否选中了任何复选框。如果未选中任何复选框,则应首先显示该复选框的警报消息。

采纳答案by Devashri B.

Hey, I found answer. It is as follows:

嘿,我找到了答案。如下:

function checkBoxselectedornot()
{

       var frm=document.forms['aspnetForm'];
       var flag=false;
       for(var i=0;i<document.forms[0].length;i++)
       {
           if(document.forms[0].elements[i].id.indexOf('chkDownloadSelectedEvent')!=-1)
           {
                 if(document.forms[0].elements[i].checked)
                 {
                      flag=true
                 }  
           }
       } 
      if (flag==true)
      {
        return true
      }else
      {
        alert('Please select at least one Event.')
        return false
      }

}

回答by I.devries

if(document.getElementById('checkBoxId').checked) {
    //checked
} else {
    //not checked
}

edit: if you want to check all checkboxes of a form you can loop through the collection:

编辑:如果您想检查表单的所有复选框,您可以遍历集合:

var inputs = document.getElementById('formId').getElementsByTagName('input');
var isChecked = false
for( var i = 0; i < inputs.length; i++) {
    if(inputs[i].type == 'checkbox' && inputs[i].checked) {
        isChecked = true;
    }
}

if(isChecked) {
    //at least one checkbox checked
}

回答by Samiksha

Server side:

服务器端:

//in your button click event :

bool flag = false;

for( int i=0; i < gridview1.rows.count ; i++)

{
if(checkbox1.checked)

 flag = true;

}

if(flag)

{

//means atleast one check box is checked

}

//在你的按钮点击事件中:

布尔标志 = 假;

for( int i=0; i < gridview1.rows.count ; i++)

{
if(checkbox1.checked)

 flag = true;

}

如果(标志)

{

//表示至少选中一个复选框

}

回答by Dave R.

You will have to add some custom Javascript to your page for the client-side alert to show. Here's a method that I've written that works with a GridView called 'GridView1' (this should be the default name if you've just dragged the control onto your ASPX page):

您必须向页面添加一些自定义 Javascript 才能显示客户端警报。这是我编写的一个方法,它与名为“GridView1”的 GridView 一起使用(如果您刚刚将控件拖到 ASPX 页面上,这应该是默认名称):

<script type="text/javascript">
    function ClientCheck() {
        var valid = false;
        var gv = document.getElementById("GridView1");

        for (var i = 0; i < gv.all.length; i++) {
            var node = gv.all[i];
            if (node != null && node.type == "checkbox" && node.checked) {
                valid = true;
                break;
            }
        }
        if (!valid) {
            alert("Invalid. Please select a checkbox to continue.");
        }

        return valid;
    }
</script>

You can see that it sets a variable to the GridViewcontrol to start with, then iterates through all the children in a forloop. If the child is a checkboxand it is checked, then we set the validvariable to true. If we get to the end of the iteration and no checked checkboxes are found, then validremains false and we execute the alert.

您可以看到它为GridView控件设置了一个变量以开始,然后循环遍历所有子项for。如果孩子是 acheckbox并且它是checked,那么我们将valid变量设置为 true。如果我们到达迭代结束并且没有找到选中的复选框,则valid保持 false 并且我们执行警报。

To link this into your GridViewon your ASPX page, first make the button column a TemplateFieldand surround the LinkButtonwith your client-side code. If you've used the designer to set up your columns, you can use the "Convert this field into a TemplateField" link in the column editor). Here's an example of the source you'll end up with:

要将其链接到您GridView的 ASPX 页面上,首先将按钮列设为aTemplateFieldLinkButton用您的客户端代码包围。如果您使用设计器来设置列,则可以使用列编辑器中的“将此字段转换为模板字段”链接)。这是您最终将获得的源示例:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1">
    <Columns>
        <asp:TemplateField HeaderText="Button Field" ShowHeader="False">
            <ItemTemplate>
                <span onclick="return ClientCheck();">
                    <asp:LinkButton ID="LinkButton1" runat="server" CommandName="IDClick" Text='<%# Eval("YourDataSourceItem") %>'></asp:LinkButton>
                </span>
            </ItemTemplate>
        </asp:TemplateField>
        // ...your remaining columns...

Using the TemplateFieldlets us add any client-side code we like. Here we're adding a spanand using onclickto call our ClientCheckmethod.

使用TemplateField可以让我们添加任何我们喜欢的客户端代码。在这里,我们添加了span和 usingonclick来调用我们的ClientCheck方法。

If you aren't bothered about the alert, you could achieve your aims by using a CustomValidatorcontrol, which executes on the server-side.

如果您不担心警报,您可以通过使用CustomValidator在服务器端执行的控件来实现您的目标。

I hope this helps.

我希望这有帮助。

回答by Amit

 <script type="text/javascript" language="javascript">
        function CheckboxSelect() {

            var LIntCtr;
            var LIntSelectedCheckBoxes = 0;

            for (LIntCtr = 0; LIntCtr < document.forms[0].elements.length; LIntCtr++) {
                if ((document.forms[0].elements[LIntCtr].type == 'checkbox') && (document.forms[0].elements[LIntCtr].name.indexOf('chkID') > -1)) {
                    if (document.forms[0].elements[LIntCtr].checked == true) {
                        LIntSelectedCheckBoxes = parseInt(LIntSelectedCheckBoxes) + 1;
                    }
                }
            }
            if (parseInt(LIntSelectedCheckBoxes) == 0) {
                alert('User(s) Must Be Selected For operation !');
                return false;
            }
        }
    </script>

回答by Ronak

   protected void OnCheckedChanged(object sender, EventArgs e)
        {
            bool flag = false;

            foreach (GridViewRow row in Grid_InvoiceGarden.Rows)
            {
                CheckBox chkItem = (CheckBox)row.FindControl("chkSelect");
                if (chkItem.Checked)
                    flag = true;
            }
            if (flag == true)
            {
                btnUpdate.Visible = true;
            }
            else
            {
                btnUpdate.Visible = false;
            }      
        }