我需要在不时有不同列的表中插入值。列和行数据从MySql更新。每个行值都在单个MySql单元格中,格式如下:
ColumnName{Delimiter}Value{BigDelimiter}Column2Name{Delimiter}Value2...
所以我拆分单元格字符串以获取列标题和值,因为用户可以重新排列列,修改,删除或插入新列。我搜索了一个解决方案,虽然我只得到空行:
private void GetDataTableValues()
{
if (dtData.Value != null)
{
try
{
LoadFields();
dgwDataMain.Items.Clear();
dgwDataMain.Columns.Clear();
foreach (Fields field in fields)
{
DataGridTextColumn column = new DataGridTextColumn();
column.Header = field.name;
column.Binding = new Binding(field.name);
dgwDataMain.Columns.Add(column);
}
if (connection.State == System.Data.ConnectionState.Broken || connection.State == System.Data.ConnectionState.Closed)
connection.Open();
command.Parameters.Clear();
DateTime dt = dtData.Value ?? DateTime.Now;
command.Parameters.Add("@date", MySqlDbType.Date, 50).Value = dt.ToString("yyyy-MM-dd");
command.CommandText = "SELECT value,team FROM sessions WHERE date=@date";
List<string> teams = new List<string>();
foreach (Control ctrl in panDataFilter.Children)
if ((ctrl as CheckBox).IsChecked == true)
teams.Add(Convert.ToString((ctrl as CheckBox).Content));
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
bool v = false;
if (teams.Contains(reader[1].ToString()) || teams.Count == 0)
v = true;
if (v)
{
DatabaseObject obj = new DatabaseObject();
List<string> str2 = new List<string>(reader[0].ToString().Split(new string[] { "</s&p>" }, StringSplitOptions.None).ToList());
obj.Items = new List<string>(str2.Count);
foreach (string str in str2)
{
List<string> item = new List<string>(str.Split(new string[] { "<&p>" }, StringSplitOptions.None).ToList());
int index = dgwDataMain.Columns.Single(c => c.Header.ToString() == item[0].ToString()).DisplayIndex;
obj.Items.Insert(index, item[1].ToString());
}
dgwDataMain.Items.Add(obj);
}
}
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ErrorCode.ToString() + ": " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
}
public class DatabaseObject
{
public List<string> Items = new List<string>();
}
答案 0 :(得分:0)
请使用 Observablecollection 绑定数据网格。通过轻松使用 observablecollection ,您可以添加或删除项目,而不需要重置数据网格的数据源。
示例代码:
observableCollection myClass = new 的ObservableCollection(); myClass.add(类)
答案 1 :(得分:0)
从datagrid中删除额外的行,只需make property ...
Canuseraddrows="false";