【问题标题】:The name 'chk' does not exist in the current context当前上下文中不存在名称“chk”
【发布时间】:2017-02-02 10:40:41
【问题描述】:

我是 c# 和 asp.net 的新手,我正在尝试制作一个管理项目集合的网络表单。
我已经设法为添加/搜索/编辑制作表格,但我在删除时遇到了一些问题。
我的错误是:
-错误 CS0103 当前上下文中不存在名称“chk”(try.aspx.cs 行:74)
-错误 CS0119 'CheckBox' 是一种类型,在给定的上下文中无效(try.aspx.cs 行:74)

我看到几个问题都出现相同的错误,但我仍然无法弄清楚我的错误在哪里。

try.aspx:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="try.aspx.cs" Inherits="keszlet_management._try" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <asp:GridView ID="KeszletGrid" runat="server" AllowPaging="True" AllowSorting="True" OnSelectedIndexChanged="KeszletGrid_SelectedIndexChanged" AutoGenerateColumns="False">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="chk" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField ItemStyle-Width="150px" DataField="Item"
                HeaderText="Item" >
<ItemStyle Width="150px"></ItemStyle>
            </asp:BoundField>
            <asp:BoundField ItemStyle-Width="150px" DataField="Type"
                HeaderText="Type" >
<ItemStyle Width="150px"></ItemStyle>
            </asp:BoundField>
            <asp:BoundField ItemStyle-Width="150px" DataField="Owner"
                HeaderText="Owner" >
<ItemStyle Width="150px"></ItemStyle>
            </asp:BoundField>
            <asp:BoundField ItemStyle-Width="150px" DataField="ID" Visible="false" >
<ItemStyle Width="150px"></ItemStyle>
            </asp:BoundField>
        </Columns>
    </asp:GridView>
    <asp:Button ID="DelBtn" runat="server" Text="Delete Selected Rows" OnClick="DelBtn_Click" />
    <asp:Label ID="Label1" runat="server" Text="Msg"></asp:Label>
</asp:Content>

try.aspx.cs:

using MySql.Data.MySqlClient;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace keszlet_management
{
    public partial class _try : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataSet();
        }

        private void DataSet()
        {
            if (!IsPostBack)
            {
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (MySqlConnection con = new MySqlConnection(constr))
                {
                    using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM items"))
                    {
                        using (MySqlDataAdapter sda = new MySqlDataAdapter())
                        {
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            using (DataTable dt = new DataTable())
                            {
                                sda.Fill(dt);
                                KeszletGrid.DataSource = dt;
                                KeszletGrid.DataBind();
                            }
                        }
                    }
                }
            }
        }

        protected void DelBtn_Click(object sender, EventArgs e)
        {
            int Count = 0;
            KeszletGrid.AllowPaging = false;
            KeszletGrid.DataBind();
            ArrayList arr = (ArrayList)ViewState["SelectedRecords"];
            Count = arr.Count;
            for(int i=0;i<KeszletGrid.Rows.Count;i++)
            {
                if(arr.Contains(KeszletGrid.DataKeys[i].Value))
                {
                    DeleteRecord(KeszletGrid.DataKeys[i].Value.ToString());
                    arr.Remove(KeszletGrid.DataKeys[i].Value);
                }
            }
            ViewState["SelectedRecords"] = arr;
            KeszletGrid.AllowPaging = true;
            DataSet();
        }
        private void GetData()
        {
            int i;
            ArrayList arr;
            if (ViewState["SelectedRecords"] != null)
                arr = (ArrayList)ViewState["SelectedRecords"];
            else
                arr = new ArrayList();
            for (i = 0; i < KeszletGrid.Rows.Count; i++)
                if (CheckBox chk = (CheckBox)KeszletGrid.Rows[i].Cells[0].FindControl("chk"))
                {
                if (chk.Checked)
                {
                    if (!arr.Contains(KeszletGrid.DataKeys[i].Value))
                    {
                        arr.Add(KeszletGrid.DataKeys[i].Value);
                    }
                }
                else
                    if (arr.Contains(KeszletGrid.DataKeys[i].Value))
                {
                    arr.Remove(KeszletGrid.DataKeys[i].Value);
                }
        }
        ViewState["SelectedRecords"] = arr;
        }
        private void DeleteRecord(string ID)
        {
            string contrs = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
            string query = "Delete From items Where id=@ID";
            MySqlConnection con = new MySqlConnection(contrs);
            MySqlCommand cmd = new MySqlCommand(query, con);
            cmd.Parameters.AddWithValue("@ID", ID);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

【问题讨论】:

标签: c# asp.net webforms


【解决方案1】:

希望对你有帮助:

for (i = 0; i < KeszletGrid.Rows.Count; i++)
    if (CheckBox chk = KeszletGrid.Rows[i].Cells[0].Controls[0] as CheckBox;

或者试试这个:

foreach(GridViewRow row in KeszletGrid.Rows) {
   if(row.RowType == DataControlRowType.DataRow) {
    CheckBox chk = row.FindControl("chk ") as CheckBox ;
   }
}

【讨论】:

  • 主要错误仍然存​​在,CheckBox 或 chk 没有改变(if(CheckBox chk = ...)
  • @kritikaTalwar,请参阅下面 Alan 的评论,您不能在 if 条件内声明变量,只能分配现有变量。
  • 感谢您的帮助@kritikaTalwar 它解决了我的问题!
  • 很高兴帮助你。
【解决方案2】:

将您的 GetData 方法更新为以下内容

您没有在 for 循环中使用代码块,并且在整个方法中也缺少一些代码块。

if 语句的缩进仅适用于一行代码,而不是多行代码。还缺少一两个右大括号

private void GetData()
{
    int i;
    ArrayList arr;
    if (ViewState["SelectedRecords"] != null)
        arr = (ArrayList)ViewState["SelectedRecords"];
    else
        arr = new ArrayList();
    for (i = 0; i < KeszletGrid.Rows.Count; i++)
    {
        CheckBox chk = null;
        if ((chk = (CheckBox)KeszletGrid).Rows[i].Cells[0].FindControl("chk"))
        {
            if (chk.Checked)
            {
                if (!arr.Contains(KeszletGrid.DataKeys[i].Value))
                {
                    arr.Add(KeszletGrid.DataKeys[i].Value);
                }
            }
            else
            {
                if (arr.Contains(KeszletGrid.DataKeys[i].Value))
                {
                    arr.Remove(KeszletGrid.DataKeys[i].Value);
                }
            }
        }
    }
}

【讨论】:

    【解决方案3】:

    这是第 74 行吗?

    if (CheckBox chk = (CheckBox)KeszletGrid.Rows[i].Cells[0].FindControl("chk"))
    

    您不能声明 chk 并在同一行的条件中使用它。试试这个:

    CheckBox chk = KeszletGrid.Rows[i].Cells[0].FindControl("chk") as CheckBox
    if (chk != null && chk.Checked) {
      // etc.
    }
    

    【讨论】:

    • 复选框位于TemplateField 中,因此它不在行中的Cell 中。需要改用行的FindControl。但是很好地抓住了 if there 的奇怪用法。
    • @user1429080 您的原始代码正在行中的单元格中查找它,不是吗?我刚刚复制了您的行并删除了类型声明。
    • 我不是 OP :-)。我相信你的建议是在正确的轨道上,但不是一直到目标。这就是我评论的原因..
    • 哈哈,原来你不是:)
    • @ColinM 我应该说声明而不是分配。
    猜你喜欢
    • 2013-10-02
    • 2014-04-22
    • 2017-06-17
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2020-11-02
    相关资源
    最近更新 更多