【发布时间】:2018-04-09 08:39:53
【问题描述】:
我无法让我的复选框列正常工作。我想要实现的是,如果条件与表中的值匹配,则在应用程序加载时选中复选框,并在每次选中或取消选中复选框时向数据库发送更新命令。
我应该如何编写它才能让它落地?我希望在没有 MVVM 的情况下实现我的目标。如果有人能帮助我摆脱困境,我将不胜感激。
这是我已经走了多远:
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn Header="Audited" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="cBox" Checked="DataGridCheckBoxColumn_Checked" Unchecked="DataGridCheckBoxColumn_Unchecked"
IsChecked="{Binding Audited, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<CheckBox x:Name="cBox" Checked="DataGridCheckBoxColumn_Checked" Unchecked="DataGridCheckBoxColumn_Unchecked"
IsChecked="{Binding Audited, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Binding="{Binding Location}" Header="Location" Visibility="Collapsed"/>
<DataGridTextColumn Binding="{Binding Date, StringFormat=MM-dd-yy}" Header="Date"/>
</DataGrid.Columns>
</DataGrid>
xaml.cs
public MainWindow()
{
InitializeComponent();
string connectionString = "datasource=; Port=; Username=; Password=";
string sMonth = DateTime.Now.ToString("MM");
string sYear = DateTime.Now.ToString("yyyy");
string sDate = DateTime.Now.ToString("yyyy-MM-dd");
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand Audit = new MySqlCommand("Select Audited from Daily.Table where MONTH(Date) = @sMonth AND YEAR(Date) = @sYear", connection);
Audit.Parameters.Add(new MySqlParameter("sDate", sDate));
try
{
connection.Open();
MySqlDataReader AuditR = Audit.ExecuteReader();
while (AuditR.Read())
{
if (AuditR["Audited"] != DBNull.Value)
{
//How I can set the checkbox to checked?
};
}
AuditR.Close();
AuditR.Dispose();
private void DataGridCheckBoxColumn_Checked(object sender, RoutedEventArgs e)
{
string connectionString = "datasource=; Port=; Username=; Password=";
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand AuditUpdate = new MySqlCommand("update Daily.Table set Audited='Yes' where ID= '" + this.txtID.Text + "'", connection);
CheckBox checkBox = sender as CheckBox;
//How can I mark the checkbox as checked from here?
}
private void DataGridCheckBoxColumn_Unchecked(object sender, RoutedEventArgs e)
{
string connectionString = "datasource=; Port=; Username=; Password=";
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand AuditUpdate = new MySqlCommand("update Daily.Table set Audited=NULL where ID= '" + this.txtID.Text + "'", connection);
CheckBox checkBox = sender as CheckBox;
//How can I mark the checkbox as unchecked from here?
}
【问题讨论】: