0

我有一个 DataGrid,它在列有标点符号时拒绝显示数据。我有以下 SQL 语句,它将结果数据放在 DataTable 中:

string statement = "SELECT TOP 200 [Test] AS [Primary key for Department records.] FROM [dbo].[Children]";

using (SqlDataAdapter adapter = new SqlDataAdapter(statement, connection))
                        {
                            adapter.Fill(dtResults);
                        }

由于.别名中的字符,DataGrid 不显示包含在 DataTable 中的信息。我通过反复试验发现了这一点。我怎样才能让数据网格用这样的列显示数据?

这是绑定代码:

dgResults.DataContext = myDataTable.AsDataView();
dgResults.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(dataGrid_AutoGeneratingColumn);
dgResults.Visibility = Visibility.Visible;

private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
   //Sets the DataGrid's headers to be TextBlocks, which solves a problem whereby underscore characters in the header are ignored.
   TextBlock block = new TextBlock();
   block.Text = e.Column.Header.ToString();
   e.Column.Header = block;
}
4

1 回答 1

1

我不确定这是否有效,但请尝试:

DataSet dset = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(statement, connection))
{
      adapter.Fill(dset);
}
DataTable dtResults = dset.Tables[0];

我希望这能解决问题。

更新:尝试摆脱标点符号。

       //this is just a list of punctuations. Database field never might not contains some of them. 
       string[] punct = new string[]{"[", "]" ,"(", ")", "{", "}", "<", ">", ":",
            ",", "-", "...", "!", "«", "»", "-", ".", "?", "\"", "'",  "'", ";", "/"};

        foreach (DataColumn column in table.Columns)
        {
            string colName = column.ColumnName;
            bool b = punct.Any(s => colName.Contains(s));
            var listOfPunct = punct.Where(s => colName.Contains(s)).ToList();
            foreach (string p in listOfPunct)
            {
                colName = colName.Replace(p, "");
            }
            column.ColumnName = colName;
        }
于 2013-04-16T15:50:37.007 回答