Passing parameter value to a new form - c#

I would like to point to a row.
Get the Oid(the parameter I want to pass).
When I click a button on the ribbon. It will open MifarePasswordForm. I would like to pass Oid to MifarePasswordForm so that the Oid can be saved in Mifare Card but I'm stuck at getting the Oid. So far, this is what I've got.
public void barButtonItem1_ItemClick()
{
staff entity = gridView.GetRow(gridView.GetSelectedRows()[0]) as staff;
entity.Oid;
MifarePasswordForm modalForm = new MifarePasswordForm();
modalForm.ShowDialog();
RefreshData();
}
This is my password form.
public MifarePasswordForm(int _iD)
{
InitializeComponent();
int iD = _iD;
}
Updated code
public void barButtonItem1_ItemClick()
{
staff entity = gridView.GetRow(gridView.GetSelectedRows()[0]) as staff;
MifarePasswordForm modalForm = new MifarePasswordForm(entity.Oid);
modalForm.ShowDialog();
RefreshData();
}
public MifarePasswordForm(int _iD)
{
InitializeComponent();
int iD = _iD;
textBox1.Text += iD;
}

What you can do is, pass your parameter to form in the constructor itself OR, make a public property and access it after creating formInstance and assign it your designated value.
e.g.
MifarePasswordForm modalForm = new MifarePasswordForm(entity.Oid);
modalForm.ShowDialog();

Related

How to use an instantiated object from one method to another?

I have these two methods:
public MessagesPage(ContactModel input)
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
ConversationsList = new ObservableCollection<ConversationModel>();
ContactModel ConversationPartner = new ContactModel();
ConversationPartner = input;
...
}
And the input which is the parameter in the method above, I also would like to use it in this method (they're in the same class)
private async void Send()
{
Guid guid = Guid.NewGuid();
string ID = guid.ToString();
ConversationModel conversationObject = new ConversationModel()
{
id = ID,
converseeID = dataClass.loggedInUser.uid,
message = Message,
created_at = DateTime.UtcNow
};
await CrossCloudFirestore.Current
.Instance
.GetCollection("contacts")
.GetDocument(ConversationPartner.id)
.GetCollection("conversations")
.GetDocument(ID)
.SetDataAsync(conversationObject);
Message = string.Empty;
}
because as you can see, in .GetDocument, it needs the id of ConversationPartner. I would get object reference not set to an instance of an object when the Send() method is called because it doesn't have access to ContactModel input in MessagesPage above.
you need to declare ConversationPartner as a class level variable, not inside of of a specific method. This will make it available throughout your class
ContactModel ConversationPartner;
public MessagesPage(ContactModel input)
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
ConversationsList = new ObservableCollection<ConversationModel>();
ConversationPartner = input;
...
}

How to use user_id from a label in another form

I am trying to create a function GetUserID() which returns the userID, which I have inserted into a label so I can use it in other forms.
But when I try to convert the label to int32 the label always seems to be empty. I think its because of where the function is placed in my code.
See:
private void Loginbtn_Click(object sender, EventArgs e)
{
var LoginFunction = new LoginFunction();
var DataTable = new DataTable();
DataTable = LoginFunction.Login(Usernametxt.Text.Trim(), Passwordtxt.Text.Trim());
int UserID = Convert.ToInt32(DataTable.Rows[0]["USER_ID"]);
if (DataTable.Rows.Count == 1)
{
CalculatorMain calculatorMain = new CalculatorMain();
MainMenu mainMenu = new MainMenu();
UserIDlbl.Text = Convert.ToString(UserID);
MessageBox.Show("ID = " + UserID);
this.Hide();
mainMenu.Show();
}
else
{
MessageBox.Show("You entered the wrong username or password");
}
}
public int GetUserID()
{
int UserID;
if (Int32.TryParse(UserIDlbl.Text, out UserID))
{
UserID = Convert.ToInt32(UserIDlbl.Text);
}
else
{
MessageBox.Show("Error, Label for UserID could not be parsed");
}
return UserID;
}
I'm not sure where else I can put this function to get it to work.
Here is the code to call the function which is used in a separate form.
private void WorkoutHistoryForm_Load(object sender, EventArgs e)
{
Login login = new Login();
int UserId = login.GetUserID();
this.sETSTableAdapter.Fill(this.gymDataSet.SETS, UserId);
}
I keep thinking there must be a better way to do this instead of storing the UserID in a label but I'm not sure how.
I would create a public class with a public field to store the UserID.
For example. let's say you have the UserID in an int variable as you have described. Now let's say you have created a public static class called Common defined with a public static field of type int called ID.
You can now store the UserID in the static field of the class:
Common.ID = UserID
Later, when you want to access the UserID from some other form, just do this:
string UserID = Common.ID
Easy peasey.
Of course, you don't need to do this in a separate class... your form itself is a class, and you can create your public field there, and call it like
Form1.UserID
Or whatever the name of your original form is where you captured the UserID...

Android - Edit SqlLite database from different activities c#

I am developing a C# Android that takes the user input and add it to a database, then in another Activity, it displays the user input with an option to edit his input again.
So I have 2 activities and 1 public class which links them together. I am using SQLLite to save the user input into a database (in the MainActivity.cs) then (in the secondActivity) it retrieves the saved value (which is the user input) from the public database (located in the public class called Class1) and displays it in a Textview.
Class1.cs
namespace App
{
public class Class1
{
public static string dpPath= Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "user.db3");
public void Insert(string Quantity, string name)
{
var db = new SQLiteConnection(Class1.dpPath);
var logintable = new LoginTable();
logintable.quantity = Quantity;
logintable.name = name;
db.Insert(logintable);
}
public void edit(string Quantity)
{
var db = new SQLiteConnection(Class1.dpPath);
var logintable = new LoginTable();
logintable.quantity = Quantity;
db.Update(logintable);
}
public void delete(int id)
{
var db = new SQLiteConnection(Class1.dpPath);
var logintable = new LoginTable();
logintable.id = id;
db.Delete(logintable);
}
public Class1()
{
//Creating database, if it doesn't already exist
if (!File.Exists(Class1.dpPath))
{
var db = new SQLiteConnection(Class1.dpPath);
db.CreateTable<LoginTable>();
}
}
public class LoginTable
{
[PrimaryKey, AutoIncrement, Column("_Id")]
public int id { get; set; } // AutoIncrement and set primarykey
[MaxLength(25)]
public string quantity { get; set; }
[MaxLength(15)]
public string name { get; set; }
public LoginTable()
{
}
}
}
MainActivity.cs
Class1 cl = new Class1():
cl.Insert(input.ToString(), name.ToLower());
SecondActivity.cs
Class1 cl = new Class1():
cl.edit(input.ToString());
var db = new SQLiteConnection(Class1.dpPath);
var table = db.Table<Class1.LoginTable>();
foreach( var item in table) {
textView.Text += item.name + " " + item.quantity;
}
Well, I am getting in the textview in the secondActivity, the input that was entered the first time (in the MainActivity) and not the one which was edited later in the SecondActivity. I thought that maybe because I have created two different instance of the Class1 and each one is working with a different Table. In addition, I have tried to initialise a public static instance of the Class1 inside the Class1 itself like that:
public class Class1 { public static Class1 cl = new Class1(); }
but did not work either, the textview is still displaying the original input and not the edited one. I need to be able to edit the database from each activitie.. Please help me to find a solution.
UPDATE
I have created a new class Class2 and I have initialise inside it a new instance of Class1 like that:
public class Class2
{
public static Class1 cl = new Class1();
}
And then i have tried to access this instance of the class1 in the Main and second activity, so in the Main my code are:
Class2.cl.Insert(input.ToString(), name.ToLower());
and in the second activity my code are:
Class2.cl.edit(input.ToString());
var db = new SQLiteConnection(Class1.dpPath);
var table = db.Table<Class1.LoginTable>(); // The issue is in this line
foreach( var item in table) {
textView.Text += item.name + " " + item.quantity;
}
So now the issue I think is in the secondActivity, the var table is getting only one table which is the one where the original input in the Main activity is stored, and when updating the value in the second activity, it is not considering the second table which stores the edited input. But still i don't know how to solve this.
On first glance it appears that your Edit() method is not correct. You have this:
public void edit(string Quantity)
{
var db = new SQLiteConnection(Class1.dpPath);
var logintable = new LoginTable();
logintable.quantity = Quantity;
db.Update(logintable);
}
But you have no way to quantify which item in the database that you wish to update; you're just creating a new item and then trying to update the table with that item. You should instead add some way to select the item you wish to edit, like this example:
public void Edit(int id, string quantity)
{
var db = new SQLiteConnection(Class1.dbPath);
var table = db.Table<Class1.LoginTable>();
var itemToEdit = table.First(f=>f.Id == id);
itemToEdit.quantity = quantity;
db.Update(itemToEdit);
}
As you can see, the example above gets the item from your table, edits the item and updates your table with the data you gave it.
Your Delete() method should follow a similar path, instead of instantiating a new object just to delete it.
Also about your update, you should consider researching the Singleton pattern. Here is a better way to handle a static object than your Class1/Class2 implementation. In your Class1 class, add the field:
public static readonly Class1 Instance = new Class1()
And then reference your instance from other classes like this:
Class1.Instance.Insert(input.ToString(), name.ToLower());
This way there is no way for you to accidentally create a new instance of Class1.

Windows forms pass List to a new form

How can I pass a variable to another form?
I created the following class:
class Cart
{
private string productName;
private int qtd;
private decimal price;
public decimal Price
{
get
{
return price;
}
set
{
price = value;
}
}
public string ProductName
{
get
{
return productName;
}
set
{
productName = value;
}
}
public int Qtd
{
get
{
return qtd;
}
set
{
qtd = value;
}
}
}
I have one form that I add values to my cart:
public partial class frmProducts : Form
{
List<Cart> cartList = new List<Cart>();
private void btnAddCart_Click(object sender, EventArgs e)
{
if(txtQtd.Text == "")
{
MessageBox.Show("Enter how many items do you want.", "Products", MessageBoxButtons.OK);
return;
}
if (Convert.ToInt32(txtQtd.Text) > Convert.ToInt32(lblQtd.Text))
{
MessageBox.Show("We onlye have " + lblQtd.Text + " items in stock.", "Products", MessageBoxButtons.OK);
return;
}
Cart cart = new Cart();
cart.ProductName = lblProductName.Text;
cart.Qtd = Convert.ToInt32(lblQtd.Text);
cart.Price = Convert.ToDecimal(lblPrice.Text);
cartList.Add(cart);
}
}
I haave another WindowsForms that will work with the cartList. How can I send the cartList to the new WindowsForms?
Let frmProcessCart be the next form where you need the cartList to proceed. For that you can use any of the following options:
Get List<Cart> in the Constructor of that form:
Which means you have to pass the cartList as to the new form through its constructor, so you will get the same instance of the list their and you can proceed with that as well. In this case the Constructor of that form looks like this:
public frmProcessCart(List<Cart> cartList)
{
// Something here if needed
}
Another option is make cartList as static field:
In this case you can access the cartList from any other forms in the applications through frmProducts.cartList, you need not to pass any instance or create any instance of the frmProducts. in this case the definition of the cartList will be like this
public partial class frmProducts : Form
{
public static List<Cart> cartList = new List<Cart>();
// Rest of code here
}
In the new windows form declare a property for the cartList. Set the property before you show that form. Then your new form can work with that property.

add data to gridView on form from another class

How can i append data to my dataGridView on form, from another class?
here is class:
class TermSh
{
public HttpWebRequest request_get_page_with_captcha;
public HttpWebResponse response_get_page_with_captcha;
public string url;
public Form1 form1;
public BindingSource bindingSource1 = new BindingSource();
public int id = 0;
public TermSh(Form1 form1)
{
this.form1 = form1;
form1.dataGridView1.DataSource = bindingSource1;
}
public void somemethod()
{
try
{
cookies += response_get_page_with_captcha.Headers["Set-Cookie"];
bindingSource1.Add(new Log(id++, DateTime.Now, cookies));
form1.dataGridView1.Update();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
and form class:
TermSh term_sh = new TermSh(this);
term_sh.somemethod();
what i do wrong? why my datagridview is empty after code executing, but with debug i see, that bindingSource1 is not empty.
how to add data?
I think , the way you are going to achieve your goal is incorrect.
first of all, I think passing Form class to a class is very very bad. and then you can simply manipulate a list and return the value and using this value (list) in your Form.
I think it's better to do like this:
[EDIT 1] this following class, is your ptimary class that has a method and this method return a new Log, and you can add this return value to the datagridview in the Form1.
class TermSh
{
public HttpWebRequest request_get_page_with_captcha;
public HttpWebResponse response_get_page_with_captcha;
public string url;
public int id = 0;
public List<Log> somemethod()
{
try
{
cookies += response_get_page_with_captcha.Headers["Set-Cookie"];
return new Log(id++, DateTime.Now, cookies); //use this return value in your Form and update datagridview
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
[EDIT 2] after that: you must prepare Log Class to be used as a collection in bindingSource (Form1.bindingSource) and update gridView. and the Following code show the Log class:
class Log
{
private int id;
private DateTime datetime;
private string log_text;
public Log(int id, DateTime datetime, string log_text)
{
this.id = id;
this.datetime = datetime;
this.log_text = log_text;
}
#region properties
public int ID { get { return id; } set { id = value; } }
public DateTime DATE_TIME { get { return datetime; } set { datetime = value; } }
public string LOG_TEXT { get { return log_text; } set { log_text = value; } }
#endregion
}
[Edit 3] and this code in the Form1, use the return value of class TermSh, and populate the dataGridView:
TermSh term_sh = new TermSh(city, type, null, null);
logList.Add(term_sh.getPageWithCaptchaConnection());
logBindingSource.DataSource = logList;
logBindingSource.ResetBindings(false);
[EDIT 4] so if you have a question that : "how use this class as a collection in bindingSource??". It's simple, you can populate a dataGridView with objects: this article is helpful.

Categories