[英]Buttonclick event based on DataGrid selected value
I am making a small application for personal use to practice WPF and C#. 我正在制作一个供个人使用的小型应用程序,以练习WPF和C#。 The application will launch games (or other applications) based on file paths which are stored in a SQL table.
该应用程序将基于存储在SQL表中的文件路径启动游戏(或其他应用程序)。 My SQL connection works fine and the data is retrieved.
我的SQL连接正常,可以检索数据。
string query = "SELECT Title, [Path] FROM GOG.dbo.Games";
I am using a DataGrid control to display the list of games, and their paths. 我正在使用DataGrid控件来显示游戏列表及其路径。 I have a 'Launch Game' button which I would like to get the currently highlighted item in the DataGrid (ie the Path) and then take the path string and therefore run it using the Process.Start() method.
我有一个“启动游戏”按钮,我想在DataGrid中获取当前突出显示的项目(即Path),然后获取路径字符串,然后使用Process.Start()方法运行它。
Here's what I have on my Button_Click but I can't get it to work: 这是Button_Click上的功能,但无法使用:
private void LaunchButton_Click(object sender, RoutedEventArgs e)
{
string gamePath = dataGrid1.SelectedItem.ToString();
Process.Start(gamePath);
}
Debug says “gamePath "System.Data.DataRowView" string”, and not the value of the actual path eg: “C:\\Windows\\System32\\calc.exe” which I think is why the application bugs out saying “The system cannot find the file specified” because “System.Data.DataRowView” is of course not a valid program. 调试显示“ gamePath“ System.Data.DataRowView”字符串”,而不是实际路径的值,例如:“ C:\\ Windows \\ System32 \\ calc.exe”,我认为这是应用程序错误提示“系统无法运行”的原因找到指定的文件”,因为“ System.Data.DataRowView”当然不是有效程序。
How can I get it to put the correct string through instead of “System.Data.DataRowView”? 如何获取正确的字符串而不是“ System.Data.DataRowView”?
dataGrid1.SelectedItem
gives you System.Data.DataRowView
object. dataGrid1.SelectedItem
为您提供System.Data.DataRowView
对象。 So you can use it directly as string. 因此,您可以将其直接用作字符串。 you must get path from it like following.
您必须像下面这样从中获取路径。
private void LaunchButton_Click(object sender, RoutedEventArgs e)
{
var row=dataGrid1.SelectedItem as System.Data.DataRowView;
if(row!=null)
{
string gamePath = row["Path"].ToString();
Process.Start(gamePath);
}
}
cast selected item of DataGrid
to DataRowView
将选定的
DataGrid
项目投射到DataRowView
DataRowView row = (DataRowView)dataGrid1.SelectedItem;
then 然后
row["ColumnName"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.