gpt4 book ai didi

c# - 如何根据我的数据库行以编程方式在 C# 中填充 WPF 网格?

转载 作者:行者123 更新时间:2023-11-30 22:17:15 24 4
gpt4 key购买 nike

我正在从 MySQL 数据库中获取结果,我想将它们显示在两列网格中。我在 MainWIndow.xaml 文件中设置了网格并添加了列定义。由于网格中的行数取决于数据库结果的数量,因此我在 C# 代码中定义了网格行。出于某种原因,grid.SetRow 和 grid.SetColumn 方法抛出以下错误:

'System.Windows.Controls.Grid.SetRow(System.Windows.UIElement, int)' cannot be accessed with an instance reference; qualify it with a type name instead.

我不知道如何解决这个问题,因为我不知道“用类型名称代替它”是什么意思。我该如何解决这个问题?

这是我的 MainWindow.xaml.cs 文件:

MySqlConnection conn = new MySqlConnection(ConnString());
try
{
conn.Open();
string query = "SELECT * FROM maps ORDER BY MapTitle";
MySqlCommand cmd = new MySqlCommand(query, conn);

MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
RowDefinition MapRow = new RowDefinition();
int CurrentRow = 0;
int CurrentColumn = 0;
while (reader.Read())
{
/* Generate the preview attachment image */
Attachment PreviewFile = new Attachment();
PreviewFile.Details(Convert.ToInt32(reader["PreviewID"]));
BitmapImage MapPreview = new BitmapImage(new Uri(ImgURL() + "/" + PreviewFile.FileName, UriKind.Relative));
MapPreview.DecodePixelWidth = 384;
MapPreview.DecodePixelHeight = 216;

/* Generate the map title header */
TextBlock MapHeader = new TextBlock();
MapHeader.Text = Convert.ToString(reader["MapTitle"]);
BrushConverter bc = new BrushConverter(); //convert hex
MapHeader.Background = (Brush)bc.ConvertFrom("#243C5E");
MapHeader.Foreground = (Brush)bc.ConvertFrom("#F2F3F5");

/* If we're in the right column, set it to the left column for the next iteration */
if(CurrentColumn == 1){
CurrentColumn = 0;
CurrentRow++;
/* Otherwise, update which column we're in. */
} else {
CurrentColumn++;
MapRow = new RowDefinition();
}

MapGrid.RowDefinitions.Add(MapRow);
/* Add the map title header to the grid in the appropriate row and column. */
MapGrid.Children.Add(MapHeader);
MapGrid.SetRow(MapHeader, CurrentRow);
MapGrid.SetColumn(MapHeader, CurrentColumn);
/* Add the map preview image to the grid in the appropriate row and column. */
MapGrid.Children.Add(MapPreview);
MapGrid.SetRow(MapPreview, CurrentRow);
MapGrid.SetColumn(MapPreview, CurrentRow);
}
}
}
catch
{
MessageBoxResult result = MessageBox.Show("A database error occurred while gathering the results.");
}
finally
{
conn.Close();
conn.Dispose();
}

这是我的网格 XAML:

<Grid Name="MapGrid" HorizontalAlignment="Center" Margin="0,25,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".4*"/>
<ColumnDefinition Width=".4*"/>
</Grid.ColumnDefinitions>
</Grid>

感谢您的宝贵时间!

最佳答案

@JSJ 完全正确。您应该使用 GridView 或 ListView。网格用于布局而不是用于显示数据。我更喜欢 ListView,您可以使用 MVVM 模式将您为数据库获得的行绑定(bind)到 ListView 。或者只是硬编码:yourListView.Items = itemsFromDb

关于c# - 如何根据我的数据库行以编程方式在 C# 中填充 WPF 网格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37874489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com