【发布时间】:2020-01-11 03:50:11
【问题描述】:
我有一个列表视图,其中有一个问题字段和两个单选按钮 - 是和否。我想将每个问题的响应添加到数据库中。我无法这样做。
这是我尝试过的-
部分 XAML 代码(列表视图位于堆栈面板内)-
<ListView HorizontalAlignment="Left" x:Name="listviewQue" Background="Azure"
ItemsSource="{Binding Questions}" ScrollViewer.CanContentScroll="False" SelectionMode="Multiple">
<ListView.ItemTemplate>
<DataTemplate>
<DockPanel>
<TextBlock DockPanel.Dock="Top" x:Name="quebox" Text="{Binding que_text}"
Style="{StaticResource ResourceKey=textblock_style }" />
<RadioButton GroupName="answergrp" Click="Yesradiobtn_Click" x:Name="yesradiobtn" DockPanel.Dock="Left">yes</RadioButton>
<RadioButton GroupName="answergrp" Click="Noradiobtn_Click" x:Name="noradiobtn" DockPanel.Dock="Right">no</RadioButton>
</DockPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
后面的代码:
private void Yesradiobtn_Click(object sender, RoutedEventArgs e)
{
string ans = "yes";
Question q = new Question();
q = listviewQue.SelectedItem as Question;
string res = SQLiteDataAccess.AddResponse(surveryId, emp[empIndex].Id, q.que_id, ans);
if (!(res == SQLiteDataAccess.SUCCESS))
{
MessageBox.Show("SQLite Exception for 'yes' radiobutton click " + res);
}
}
private void Noradiobtn_Click(object sender, RoutedEventArgs e)
{
string ans = "no";
Question q = new Question();
q = listviewQue.SelectedItem as Question;
string res = SQLiteDataAccess.AddResponse(surveryId, emp[empIndex].Id, q.que_id, ans);
if (!(res == SQLiteDataAccess.SUCCESS))
{
MessageBox.Show("SQLite Exception for 'no' radiobutton click : " + res);
}
}
这是用于插入数据库的sqlite函数:
public static string AddResponse(string sid,string eid,int qid,string answer)
{
try
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("insert into RESPONSE values ('" + sid + "','" + eid + "'," + qid + ",'" + answer + "')");
}
return SUCCESS;
}
catch(Exception e)
{
return FAILURE +": exception e = "+e;
}
}
我得到的异常消息是 -
\System.NullReferenceException: 'Object reference not set to an instance of an object.'
q was null.
我怎样才能实现它?
更新问题类 -
namespace Version2._0
{
public class Question
{
public int que_id { get; set; }
public string que_text { get; set; }
private bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set
{
isSelected = value;
// SQLiteDataAccess.AddResponse(surveryId, emp[empIndex].Id, item.que_id, ans);
// how can I get the surveyId and emp[empIndex].Id here
}
}
}
}
【问题讨论】:
-
您根本不应该使用 Click 事件处理程序。相反,将其中一个 RadioButtons 的 IsChecked 属性绑定到 Question 类中的布尔属性。然后对视图模型中该属性的更改做出反应。
-
哦!我有一个``` public Boolean IsSelected { get;放; }``` 在我的 Question 类中,我如何在这里使用单选按钮?
-
哦,对不起!你的意思是这样 - `public Boolean IsSelected { get { return IsSelected; } set { // 我的代码放在这里 } } `
-
除了
return IsSelected将是return isSelected,即使用属性的支持字段。否则你会得到一个 StackOverflowException。 -
查看我在您的问题中所做的编辑。作为说明,我认为您根本不需要设置或绑定 GroupName。
标签: c# wpf listview radio-button