Show MessageBox that contain sql data when button

2019-08-25 08:56发布

I'm making a program that showing my data into image and label. Here's an example of my program when not clicked:

When not Clicked: Screen Shot

When Clicked Screen Shot

The question is when I click one of those images. How to show the id ("id_movie" in my SQL) of that image into a MessageBox ViewModel Class.

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; }
}

Click Class

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");
    }
}

1条回答
Explosion°爆炸
2楼-- · 2019-08-25 09:32

If you just need the data of the database, you could give the dt as a parameter when initializing the 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);
    }
}

And in the Execute method you access the vModel or Library field, depending on what you gave as a parameter and present the data.

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]);
    }
}
查看更多
登录 后发表回答