错误说明:“Apple”列已属于此数据表

错误说明:“Apple”列已属于此数据表

问题描述:

下面的代码是我原来的一个例子,它收到了这篇文章标题中列出的错误。



The code below is an example of my original which is receiving the listed error in the title of this post.

Dim dt As New DataTable
    dt.Clear()
        dt.Columns.Add("apple")
        dt.Columns.Add("apple 1")
    Dim mr As DataRow
        mr = dt.NewRow
        mr("apple") = "Macbook"
        mr("apple 1") = "ipod"
    dt.Rows.Add(mr)
    GridView1.DataSource = dt
    GridView1.DataBind()





我尝试过:



谷歌搜索此错误购买我的错误与所有错误不同。



What I have tried:

Googling this error buy my error is just different from all.

列名中的空格很麻烦!

如果你必须使用名称中的空格,那么列名应该用方括号括起来 []

或者,从 ColumnName 中删除​​空格并使用 Caption 属性友好名称的DataColumn



=====这是我尝试过的C#== ========

Spaces in column names are troublesome!
If you must use the space in the name, then the column name should be enclosed in square brackets [].
Alternatively, remove the space from the ColumnName and use the Caption property of the DataColumn for the friendly name.

===== Here's the C# of what I tried ==========
using System;
using System.Data;
using System.Web.UI;

namespace CP_WebDataColumn
{
  public partial class About : Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      DataTable dt = new DataTable();
      dt.Clear();
      dt.Columns.Add("Apple");
      DataColumn col = dt.Columns.Add("Apple 1");
      DataRow mr = dt.NewRow();
      mr["Apple"] = "Macbook";
      mr["Apple 1"] = "ipod";
      dt.Rows.Add(mr);
      GridView1.DataSource = dt;
      GridView1.DataBind();
    }
  }
}





这是About.aspx:



Here's the About.aspx:

<%@ Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="CP_WebDataColumn.About" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%: Title %>.</h2>
    <h3>Your application description page.</h3>
    <p>Use this area to provide additional information.</p>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
</asp:Content>