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:
When Clicked
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");
}
}
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]);
}
}
Related
I am having trouble to show MySQL query data on LiveCharts 2 PieChart. The issue is the values does not appears on the chart. I already tried a lot of possible solutions but It still did not succeed.
My code:
public ObservableCollection<ISeries> InvestedMoney { get; set; } //to XAML binding
private ObservableCollection<PieChartModel> pieChartData = new ObservableCollection<PieChartModel>();
pieChartData = dbConnect.GetPieChartData();
InvestedMoney = new ObservableCollection<ISeries>
{
new PieSeries<PieChartModel>
{
Values = pieChartData,
Fill = new SolidColorPaint(SKColors.Red),
}
};
DataContext = this;
My dbConnect class:
public ObservableCollection<PieChartModel> GetPieChartData()
{
ObservableCollection<PieChartModel> pieChartData = new ObservableCollection<PieChartModel>();
if (Connect())
{
string query = "SELECT name, SUM(moneyInvested) AS moneyInvested FROM investments GROUP BY name;";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
pieChartData.Add(new PieChartModel
{
name = reader.GetString(0),
moneyAmount = reader.GetDouble(1),
});
}
Connect_Close();
}
return pieChartData;
}
And the PieChartModel:
public string name { get; set; }
public double moneyAmount { get; set; }
I would like to refresh the PieChart everytime when new record is added to the database.
i am new to xamarin, i need to easily link a grid (or something similar) to my MySql database table.
In WinForms I had done it by putting a grid with the designer and with a few lines of code, but instead with Xamarin I can't do anything ...
My current project is a XamarinForm with the default "tab" preset.
Here is the WinForm code:
try
{
MySqlConnection cnn;
string connetionString = "server=sql7.freesqldatabase.com;database=------;port=----;uid=-------;pwd=------;";
cnn = new MySqlConnection(connetionString);
DataTable dt = new DataTable();
MySqlCommand cmd;
cnn.Open();
cmd = cnn.CreateCommand();
cmd.CommandText = "SELECT * from Products";
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
adapter.Fill(dt);
dataGridView1.DataSource = dt; //dataGridView WinFrom component
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Is there a way to do this in Xamarin?
(my goal is to display all the db table in one page)
Welcome to SO!
Although there is not the same way that Xamarin can use DataTable as Source directly, but there is an another way to convert Table Date and make it used for Control(Such as CollectionView, DataGrid, etc).
For example, ItemSource can be set as follows:
MyDataGrid.ItemsSource = await TodoItemDatabase.Database.Table<TodoItem>().ToListAsync();
Here the TodoItem is the Model of table data, you need to create it in Xamarin Forms manually. Then the app will convert the table data to list data according to the model style.
using SQLite;
public class TodoItem
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Name { get; set; }
public string Notes { get; set; }
public bool Done { get; set; }
}
About using Databases in Xamarin, you can refer to this official document.And there is a sample project for reference. Above code TodoItemDatabase class also based on this sample.
Here is the TodoItemDatabase class:
public class TodoItemDatabase
{
static readonly Lazy<SQLiteAsyncConnection> lazyInitializer = new Lazy<SQLiteAsyncConnection>(() =>
{
return new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);
});
public static SQLiteAsyncConnection Database => lazyInitializer.Value;
static bool initialized = false;
public TodoItemDatabase()
{
InitializeAsync().SafeFireAndForget(false);
}
async Task InitializeAsync()
{
if (!initialized)
{
if (!Database.TableMappings.Any(m => m.MappedType.Name == typeof(TodoItem).Name))
{
await Database.CreateTablesAsync(CreateFlags.None, typeof(TodoItem)).ConfigureAwait(false);
}
initialized = true;
}
}
public Task<List<TodoItem>> GetItemsAsync()
{
return Database.Table<TodoItem>().ToListAsync();
}
public Task<List<TodoItem>> GetItemsNotDoneAsync()
{
return Database.QueryAsync<TodoItem>("SELECT * FROM [TodoItem] WHERE [Done] = 0");
}
public Task<TodoItem> GetItemAsync(int id)
{
return Database.Table<TodoItem>().Where(i => i.ID == id).FirstOrDefaultAsync();
}
public Task<int> SaveItemAsync(TodoItem item)
{
if (item.ID != 0)
{
return Database.UpdateAsync(item);
}
else
{
return Database.InsertAsync(item);
}
}
public Task<int> DeleteItemAsync(TodoItem item)
{
return Database.DeleteAsync(item);
}
}
And Constants class which contains database name and other things.
public static class Constants
{
public const string DatabaseFilename = "TodoSQLite.db3";
public const SQLite.SQLiteOpenFlags Flags =
// open the database in read/write mode
SQLite.SQLiteOpenFlags.ReadWrite |
// create the database if it doesn't exist
SQLite.SQLiteOpenFlags.Create |
// enable multi-threaded database access
SQLite.SQLiteOpenFlags.SharedCache;
public static string DatabasePath
{
get
{
var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(basePath, DatabaseFilename);
}
}
}
With a list of struct as the Datasource for a Listbox, I am getting the Object.ToString() rather than the expected field value from the struct
This was working OK when I assigned a DataTable as the DataSource after setting the DisplayMember.
However, I wanted to try using a list of struct (int ID, String Name) instead and despite having set DisplayMember to "Name" before assigning the Datasource to the List I get the row object.toString().
Any help would be fantastic.
On Form Load:
private void frmTestProof_Load(object sender, EventArgs e)
{
TestMaker tm = new TestMaker();
tm.LoadMakersToListbox(ref lstboxMaker);
}
class TestMaker
{
public struct MakerRecord
{
public int MakerID;
public String MakerName;
public MakerRecord(int ID, String Name)
{
MakerID = ID;
MakerName = Name;
}
}
public SQLiteConnection DBconn;
public String thisPath = "";
public SQLiteCommand sqlCommand = new SQLiteCommand();
public DataSet dsMaker = new DataSet();
public SQLiteDataAdapter daMaker = new SQLiteDataAdapter();
public TestMaker()
{
thisPath = "c:\\sqlite\\abc.db";
DBconn = new SQLiteConnection(String.Format("Data Source={0};Version=3;", thisPath));
DBconn.Open();
sqlCommand.Connection = DBconn;
sqlCommand.CommandType = CommandType.Text;
}
public List<MakerRecord> GetListOfMakers()
{
List<MakerRecord> makerList = new List<MakerRecord>();
String sqlMaker = "SELECT ID, VehicleMakerName FROM VehicleMakers WHERE VehicleMakerName IS NOT NULL"
;
sqlCommand.CommandText = sqlMaker;
daMaker.SelectCommand = sqlCommand;
try
{
daMaker.Fill(dsMaker, "Makers");
makerList = (from item in dsMaker.Tables["Makers"].AsEnumerable()
select new MakerRecord()
{
MakerID = Convert.ToInt32(item["ID"]),
MakerName = item["VehicleMakerName"].ToString()
}).ToList();
}
catch (Exception ex)
{
MessageBox.Show(String.Format("List of Makers - Error ({0})", ex.Message));
}
return makerList;
}
public void LoadMakersToListbox(ref ListBox lb)
{
lb.Items.Clear();
lb.ValueMember = "MakerID";
lb.DisplayMember = "MakerName";
lb.DataSource = GetListOfMakers();
}
}
Change public String MakerName; to public string MakerName {get;set;} and public int MakerID; to public int MakerID {get;set;}
I am trying to write login app.
My problem is that Service gives me ArrayOfXElement instead of an object.
And I do not know how to get to this object.
Here is the code:
StartPage.xaml.cs
using (...);
namespace MyFirstProject
{
public sealed partial class StartPage : Page
{
ServiceReference1.Service1Client MyService;
public StartPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
MyService = new ServiceReference1.Service1Client();
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.GetSinglePassCmdResponse h = MyService.GetSinglePassCmdAsync(new ServiceReference1.Pass { nickName = tBoxNick_log.Text }).Result;
Now I thought that in h I have object and I can do smth like this:
testBlock.Text = "nickname: " + h.nickname + " password: " + h.pass;
}}}
but I got error that GetSinglePassCmdResponse does not contain a definition for 'nickname'
IService1.cs
[OperationContract]
Pass GetSinglePassCmd(Pass Pass);
[DataContract]
public partial class Pass
{
[DataMember]
public string nickName { get; set; }
[DataMember]
public string password { get; set; }
[DataMember]
public Nullable<System.DateTime> lastLogDate { get; set; }
Service1.svc
public Pass GetSinglePassCmd(Pass Pass)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("SELECT * FROM Passwords WHERE nickName=#nickName", con);
cmd.Parameters.AddWithValue("#nickName", Passwords.nickName);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
Pass pass = new Pass();
int i = 0;
if (ds.Tables[0].Rows.Count > 0)
{
//assign dataset values to array
pass.nickName = ds.Tables[0].Rows[i]["nickName"].ToString();
pass.password = ds.Tables[0].Rows[i]["password"].ToString();
pass.lastLogDate = DateTime.Parse(ds.Tables[0].Rows[i]["lastLogDate"].ToString());
}
else pass = null;
return pass;
}
And in MyFirstProject->ServiceReferences->ServiceReference1->Reference.cs->GetSinglePassCmdResponse I got
public partial class GetSinglePassCmdResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tempuri.org/", Order=0)]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
public MyFirstProject.ServiceReference1.ArrayOfXElement GetSinglePassCmdResult;
public GetSinglePassCmdResponse() {
}
public GetSinglePassCmdResponse(MyFirstProject.ServiceReference1.ArrayOfXElement GetSinglePassCmdResult) {
this.GetSinglePassCmdResult = GetSinglePassCmdResult;
}
}
Could anyone help me please... ?
PS I have also tried this:
testBlock.Text = "nickname: " + h.GetSinglePassCmdResult.nickname + " password: " + h.GetSinglePassCmdResult.pass;
I'm working on some code that executes MDX queries against sql server analysis service. The MDX query is being executed twice on the same thread and I have no idea why. The query should only execute once
Below is some of the code. can anyone help please.
private void Start_QueryWorkers()
{
foreach (QueryThread th in _QueryWorkers)
{
SSASQuery q = new SSASQuery();
q.QueryText = "SELECT NON EMPTY { [Measures].[count] } ON COLUMNS FROM [cube]";
q.queryThread = th;
th.WorkerThread.RunWorkerAsync(q);
}
}
private void QueryWorkerThread_DoWork(object sender, DoWorkEventArgs e)
{
SSASQuery q = e.Argument as SSASQuery;
OleDbCommand cmd = new OleDbCommand(q.QueryText, q.queryThread.conn);
OleDbDataReader rdr = cmd.ExecuteReader();
rdr.Close();
}
private void btnStartTest_Click(object sender, EventArgs e)
{
string strConnString = "Provider=MSOLAP;Data Source=SRV001" + ";Initial Catalog=Cube_2015" + ";";
_QueryWorkers.Clear();
{
QueryThread thread = new QueryThread(strConnString);
thread.WorkerThread = new BackgroundWorker();
thread.WorkerThread.DoWork += new DoWorkEventHandler(this.QueryWorkerThread_DoWork);
_QueryWorkers.Add(thread);
}
Start_QueryWorkers();
}
}
class SSASQuery
{
public string QueryText { get; set; }
public QueryThread queryThread { get; set; }
}
class QueryThread
{
public QueryThread(string connString)
{
this.connString = connString;
conn = new OleDbConnection(connString);
conn.Open();
queryList = new SortedList();
}
public SortedList queryList { get; set; }
public string threadName { get; set; }
public string connString { get; set; }
public OleDbConnection conn;
public BackgroundWorker WorkerThread { get; set; }
}
}
solved. code was ok, it was a problem in the connection string execting the query twice