在c中单击按钮时显示包含sql数据的messagebox#

ecfsfe2w  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(213)

我正在制作一个程序,将我的数据显示成图像和标签。以下是我的程序在未单击时的示例:
未单击时:

单击时

问题是当我点击其中一张图片时。如何在messagebox viewmodel类中显示该图像的id(在我的sql中为“id\u movie”)。

public class VModel
{
    public VModel()
    {
        Clicked = new ClickedCommand(this);
        DataTable dt = new DataTable();

        using (MySqlConnection connection = new MySqlConnection("SERVER=localhost;" + "DATABASE=library;" + "UID=root;" + "PASSWORD=;"))
        {
           MySqlDataAdapter adapter = new MySqlDataAdapter();
           adapter.SelectCommand = new MySqlCommand("Select * from movie_list", connection);
           adapter.Fill(dt);
        }
        Library = dt.DefaultView;
    }
    public ICommand Clicked { get; set; }
    public DataView Library { get; private set; }
}

单击“类”

internal class ClickedCommand : ICommand
{
    private VModel vModel;

    public ClickedCommand(VModel vModel)
    {
        this.vModel = vModel;
    }

    public event EventHandler CanExecuteChanged { add { } remove { } }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        MessageBox.Show("the id that got clicked");
    }
}
qni6mghb

qni6mghb1#

如果你只需要数据库的数据,你可以给 dt 作为参数初始化 ClickedCommand .

public class VModel
{
    public ICommand Clicked { get; set; }
    public DataView Library { get; private set; }

    public VModel()
    {
        DataTable dt = new DataTable();

        using (MySqlConnection connection = new MySqlConnection("SERVER=localhost;" + "DATABASE=library;" + "UID=root;" + "PASSWORD=;"))
        {
            MySqlDataAdapter adapter = new MySqlDataAdapter();
            adapter.SelectCommand = new MySqlCommand("Select * from movie_list", connection);
            adapter.Fill(dt);
        }

        var Library = dt.DefaultView;
        // this = viewModel or Library as parameter
        var Clicked = new ClickedCommand(this);
    }
}

而在 Execute 方法访问 vModel 或者 Library 字段,这取决于您作为参数提供的内容并显示数据。

internal class ClickedCommand : ICommand
{
    private VModel _vModel;
    // private DataView _library;

    public ClickedCommand(VModel vModel)
    {
        _vModel = vModel;
        // _library = library;
    }

    public void Execute(object parameter)
    {
        int rowIndex;
        int.TryParse(((string[])parameter)[0], out rowIndex);
        var stringToSearch = ((string[]) parameter)[1];
        // however you access it here.
        MessageBox.Show(_vModel.Library[rowIndex][stringToSearch]);
        // MessageBox.Show(_library[rowIndex][stringToSearch]);
    }
}

相关问题