My problem is to insert data to firebase in xamarin form.
This is my CreateAccount.xaml
`
<Picker
Title="Select Security Question"
TextColor="Black"
HorizontalOptions="StartAndExpand"
FontSize="Medium"
WidthRequest="250"
TitleColor="Black"
x:Name="entryField_SecurityQuestion"
>
<Picker.Items
>
<x:String>
Who is your first love?
</x:String>
<x:String>
what subject you failed?
</x:String>
<x:String>
What is the name of your dog?
</x:String>
<x:String>
Who is your first kiss?
</x:String>
</Picker.Items>
</Picker>
codebehind.cs
async public void signButton_Clicked(System.Object sender, System.EventArgs e)
{
Picker picker = sender as Picker;
//this is how I manage my some ID from my front end
string firstName = entryField_Firstname.Text;
string lastName = entryField_Lastname.Text;
string contactNumber = entryField_PhoneNumber.Text;
string securityQuestion = picker.SelectedItem.ToString(); // this line is my trial and error, I tried some code but I cant insert data to database
Customer customer = new Customer();
customer.FirstName = firstName;
customer.LastName = lastName;
customer.SecurityQuestion = securityQuestion;//this one also, this is my trial and error approach
customer.ContactNumber = contactNumber;
var Savedata = await customerRepo.Save(customer);
}
`
I expect that, I can get the picker's item, and save it to database.
Any link that will be posted related to my post, will be appreciated. Thank you so much
If you want to get the Picker's SelectedItem, you need to refer to the x:Name="entryField_SecurityQuestion" of your picker not Picker picker = sender as Picker;,just as Jason said.
You can refer to the following code:
private void signButton_Clicked(object sender, EventArgs e)
{
// remove the following code
//Picker picker = sender as Picker;
string securityQuestion = entryField_SecurityQuestion.SelectedItem.ToString();
Customer customer = new Customer();
customer.FirstName = firstName;
customer.LastName = lastName;
customer.SecurityQuestion = securityQuestion;
}
Related
I have a function which is receiving parameters from another function and I have to pass these parameters to a button when it's execution get's complete !
async void CallCompanyApi(String CompanyGp, string CompanyId)
{
First.IsVisible = false;
Second.IsVisible = true;
// Next_Clicked(CompanyGp,CompanyId)
}
private void Next_Clicked(object sender, EventArgs e)
{
}
I have to pass these 2 parameters to that button !
you need to create class level variables to store these values
string _CompanyGp;
string _CompanyId;
async void CallCompanyApi(String CompanyGp, string CompanyId)
{
First.IsVisible = false;
Second.IsVisible = true;
// store the parameters in the class level variables
_CompanyGp = CompanyGp;
_CompanyId = CompanyId;
}
private void Next_Clicked(object sender, EventArgs e)
{
// you can now just reference _CompanyGp and _CompanyId
}
FYI, this is basic C# and really has nothing specific to do with Xamarin
Welcome to SO!
If CallCompanyApi and Next_Clicked located in different class, you can store them in Xamarin Forms by using Preferences.
using Xamarin.Essentials;
async void CallCompanyApi(String CompanyGp, string CompanyId)
{
First.IsVisible = false;
Second.IsVisible = true;
//Next_Clicked(CompanyGp,CompanyId)
Preferences.Set("CompanyGp", CompanyGp);
Preferences.Set("CompanyId", CompanyId);
}
Then in another class, click button will get them:
private void Next_Clicked(object sender, EventArgs e)
{
var CompanyGp = Preferences.Get("CompanyGp", "default_value");
var CompanyId = Preferences.Get("CompanyId", "default_value");
}
Else if they are in the same class, you can use the way as Jason's said.
============================Update=========================
You can set a default value if needed, such as follow:
var CompanyGp = Preferences.Get("CompanyGp", "Company_A");
var CompanyId = Preferences.Get("CompanyId", "1");
Defalut CompanyGp is Company_A, and default CompanyId is 1.
Im trying to understand how all is connected and I need some help.
So far I can do insert, update, delete into sqlite database but I cant make the UI show the changes from the database automatically without me to update the ItemsSource on the ListView whenever changes are made to the database. i.e.:
In my App.xaml.cs
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
//Connection to the database and create the table if not there
string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
SQLiteConnection conn = new SQLiteConnection(path);
conn.CreateTable<CheckListItemModel>();
}
Than in my MainPage.xaml i have a simple page with two buttons and the Listview
<Page
x:Class="Personal_Checklist_2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Personal_Checklist_2"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="100" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal" >
<Button Content="Add Sample To Db" Click="Add_Sample_To_Db_Click" Margin="10,0,10,0" />
<Button Content="Clear Tasks" Click="Clear_Tasks_Click" />
</StackPanel>
<ListView Name="lvListView" Grid.Row="1" >
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}" />
<TextBlock Text="{Binding Id}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Page>
In MainPage.xaml.cs code-behind I also keep as simple as I know just to add new row into the table and clear the table
using Personal_Checklist_2.DataModels;
using System.IO;
using System.Linq;
using SQLite;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System.Collections.ObjectModel;
namespace Personal_Checklist_2
{
public sealed partial class MainPage : Page
{
static string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
ObservableCollection<CheckListItemModel> Tasks = new ObservableCollection<CheckListItemModel>();
public MainPage()
{
this.InitializeComponent();
using (var conn = new SQLiteConnection(path))
{
var query = conn.Table<CheckListItemModel>();
Tasks = new ObservableCollection<CheckListItemModel>(query.ToList());
lvTasksList.ItemsSource = Tasks.ToList(); //<<<--- If I dont do this, list is not updated
}
}
private void Add_Sample_To_Db_Click(object sender, RoutedEventArgs e)
{
var Task = new CheckListItemModel()
{
taskTitle = "Sample Task"
};
using (var conn = new SQLiteConnection(path))
{
conn.Insert(Task);
var query = conn.Table<CheckListItemModel>();
Tasks = new ObservableCollection<CheckListItemModel>(query.ToList());
lvTasksList.ItemsSource = Tasks.ToList(); //<<<--- If I dont do this, list is not updated
}
}
private void Clear_Tasks_Click(object sender, RoutedEventArgs e)
{
using (var conn = new SQLiteConnection(path))
{
conn.DeleteAll<CheckListItemModel>();
var query = conn.Table<CheckListItemModel>();
Tasks = new ObservableCollection<CheckListItemModel>(query.ToList());
lvTasksList.ItemsSource = Tasks.ToList(); //<<<--- If I dont do this, list is not updated
}
}
}
}
The database table model looks like this CheckListItemModel.cs
using SQLite;
using System;
using System.ComponentModel;
namespace Personal_Checklist_2.DataModels
{
class CheckListItemModel : INotifyPropertyChanged
{
#region Private fields on DataModel
private string _taskTitle;
#endregion
#region Public properties on DataModel
[PrimaryKey, AutoIncrement]
public int taskId { get; set; }
public string taskTitle
{
get { return _taskTitle; }
set { _taskTitle = value; NotifyPropertyChanged("taskTitle"); }
}
#endregion
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
But it doesn't look right to me this way. Is there a way to achieve this without setting the listview.ItemsSource everytime some changes in db.sqlite and how?
You cast your ObservableCollection toList() thats why it doesnt update. Change it to:
lvTasksList.ItemsSource = Tasks;
And when you add an item you dont have to read again from db
private void Add_Sample_To_Db_Click(object sender, RoutedEventArgs e)
{
var Task = new CheckListItemModel()
{
taskTitle = "Sample Task"
};
using (var conn = new SQLiteConnection(path))
{
conn.Insert(Task);
}
Tasks.Add(Task);
}
You're creating a new ObservableCollection every time, instead of binding to a single ObservableCollection and changing the items in it.
So, keep Tasks as a single ObservableCollection and update its content based on the DB query results.
I have database with images in folder on my server. To display this images I'am using DataList control. ItemTemplate include also a LinkButton
<asp:LinkButton ID="wybierzZdjecieBtn" OnClick="choosePhotoButton_Click" CommandArgument='<%#Eval("PhotoLinkAddress")%>' CssClass="wybierzZdjecieButton" runat="server">Choose photo</asp:LinkButton>
To receiving Value from LinkButton CommandArgument i'am using this method:
protected void choosePhotoButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)(sender);
string photoLinkAddressVar = button.CommandArgument.ToString();
Response.Write(PhotoLinkAddressVar);
}
This works fine, no problems. But this is not what I want achieve. My intentions is send this variable "PhotoLinkAddressVar" to this method:
protected void addNewNews_Click(object sender, EventArgs e)
{
string trescStatus = "czeka";
string autor = Session["userName"].ToString();
DateTime data = DateTime.Now;
string dataFormat = "";
dataFormat = data.ToString("dd/MM/yyyy H:mm");
string CS = ConfigurationManager.ConnectionStrings["wiadomosciConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
string dodaj = "Insert into News (TytulNews, TrescNews, Autor, Data, Kategoria, Dotyczy, PhotoLinkAddress, Status) values (#TytulNews, #TrescNews, #Autor, #Data, #Kategoria, #Dotyczy, #PhotoLinkAddress, #Status)";
SqlCommand com = new SqlCommand(dodaj, con);
com.Parameters.AddWithValue("#TytulNews", tytulNewsTextBox.Text);
com.Parameters.AddWithValue("#TrescNews", trescTextBox.Text);
com.Parameters.AddWithValue("#Autor", autor);
com.Parameters.AddWithValue("#Data", dataFormat);
com.Parameters.AddWithValue("#Kategoria", kategoria.SelectedValue.ToString());
com.Parameters.AddWithValue("#Dotyczy", dotyczy.SelectedValue.ToString());
com.Parameters.AddWithValue("#PhotoLinkAddress", photoLinkAddressVar);
com.Parameters.AddWithValue("#Status", trescStatus);
com.ExecuteNonQuery();
}
}
User have to choose photo before press "Add News", because if He doesn't do that, he will receive error message. I dont know, how do that. I Was trying declare some kind public variable before PageLoad and do something like this:
protected void choosePhotoButtonButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)(sender);
photoLinkAddressVar = button.CommandArgument.ToString();
}
but that method won't declare the variable. Do You have any idea, how can I achieve that ?.
You could use also the ViewState.
protected void choosePhotoButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)(sender);
string photoLinkAddressVar = button.CommandArgument.ToString();
View["photoLinkAddressVar"]=photoLinkAddressVar;
Response.Write(PhotoLinkAddressVar);
}
Then in the addNewNews_Click method, you coukld retrieve this value with the following way:
com.Parameters.AddWithValue("#PhotoLinkAddress", ViewState["photoLinkAddressVar"]);
For further documantation about ViewState please look here.
i m writing a web application and i have a problem in one on my pages!
i design a admin page and i want to log in before user enter in this page!
there are three RequiredFieldValidator and a button(AddButton) in my page and i want to check the fields when user click the button but when the page is loaded the validation is checked and visual studio throw a exception:
"The ControlToValidate property of 'NameValid' cannot be blank" NameValid is one of my Validation controls in page!
and another question: what is the advantage of (using) block when you work with databases and files?
my class is here:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer == null)
{
//a page for log in
Response.Redirect("~/LogIn.aspx");
}
}
protected void Page_Error(object sender, EventArgs e)
{
Response.Clear();
Response.Write("<h2>Exception</h2><br />");
Response.Write(Server.GetLastError().Message);
Server.ClearError();
}
protected void AddButton_Click(object sender, EventArgs e)
{
const string ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\rasoul\sourcecode\ASP-PROJECTS\UniversityDataBase\DataBase\PersonDataBase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
using (SqlConnection con=new SqlConnection(ConnectionString))
{
string ID = IDField.Text.Trim();
string Name = NameField.Text.Trim();
string LastName = LastNameField.Text.Trim();
DataSet data = new DataSet();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = String.Format("insert into StudentTable values('{0}','{1}','{2}')", ID, Name, LastName);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
what should i do?
In required field validators you MUST specify the ControlToValidate - the control you which to validate that it is required.
MSDN Description - Use the ControlToValidate property to specify the input control to validate. This property must be set to the ID of an input control for all validation controls except the CustomValidator control, which can be left blank. If you do not specify a valid input control, an exception will be thrown when the page is rendered. (Source: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basevalidator.controltovalidate.aspx)
The advantage of the using block is it ensures the correct use of IDisposable objects.
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
is equivalent to
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
Source: http://msdn.microsoft.com/en-us/library/yh598w02.aspx
you have to check controltovalidate. you have to assign controller.
I want to build a form where users can enter some data in a few text boxes and click the "Add" button and have the the data appear in a grid or something like it. They need to be able to enter multiple rows.
Then when they are done they can click the "Save" button to save the data to the database.
How do I get the data from from the text boxes into the "grid"?
EDIT
Here's what I have so far
protected void Page_Load(object sender, EventArgs e)
{
DataTable myDataTable = new DataTable();
DataColumn dc1 = new DataColumn("Employee");
myDataTable.Columns.Add(dc1);
DataColumn dc2 = new DataColumn("Category");
myDataTable.Columns.Add(dc2);
DataColumn dc3 = new DataColumn("Description");
myDataTable.Columns.Add(dc3);
DataColumn dc4 = new DataColumn("P/S/N");
myDataTable.Columns.Add(dc4);
DataColumn dc5 = new DataColumn("Hours");
myDataTable.Columns.Add(dc5);
DataColumn dc6 = new DataColumn("WeekEnding");
myDataTable.Columns.Add(dc6);
}
protected void btnAddToGrid_Click(object sender, EventArgs e)
{
DataRow row = myDataTable.NewRow();// i'm getting error here sayind myDataTable does not exist
row["Employee"] = LoginName1.ToString();
row["Category"] = ddlCategory.SelectedValue;
row["Description"] = txtDescription.Text;
row["P/S/N"] = ddlPSN.SelectedValue;
row["Hours"] = ddlHours.SelectedValue;
row["WeekEnding"] = txtWeekEnding.Text;
myDataTable.Rows.Add(row);
Ok your first problem from your comment:
i'm getting error here sayind myDataTable does not exist
Is because you defined your table in the Page_Load and then it goes out of scope at the end of the function. It sounds like you don't understand the basic concepts of ASP.NET and what you are trying to do.
Here is a quick and dirty untested solution to your problem but I must stress that you should try and understand why this solution works before trying to extend it or do more in ASP.NET. I hope my 10 minutes of my time helps you get a good start into understanding C# and ASP.NET.
[Serializable]
public class YourData
{
public string Employee { get; set; }
public string Category { get; set; }
public string Description { get; set; }
public string P_S_N { get; set; }
public string Hours { get; set; }
public string WeekEnding { get; set; }
}
// Used to add your list of data to the viewstate cache
// (There are other ways to store data between posts but I am trying to keep it simple)
public void SetYourCachedData(List<YourData> data)
{
ViewState["YourDataCache"] = data;
}
// Used to get your save data so far
public List<YourData> GetYourCachedData()
{
return ViewState["YourDataCache"] == null ?
new List<YourData>() : (List<YourData>)(ViewState["YourDataCache"]);
}
protected void Page_Load(object sender, EventArgs e)
{
// Do nothing
}
protected void btnAddToGrid_Click(object sender, EventArgs e)
{
// Get the data and store it in the ViewState to cache it between post backs
// Assuming one record added with each click.
List<YourData> data = GetYourCachedData();
data.Add(new YourData()
{
Employee = LoginName1.ToString(),
Category = ddlCategory.SelectedValue,
Description = txtDescription.Text,
P_S_N = ddlPSN.SelectedValue,
Hours = ddlHours.SelectedValue,
WeekEnding = txtWeekEnding.Text
});
// You can bind to any type of collection easily.
// You don't need to use a DataTable with a GridView
yourGrid.DataSource = data;
yourGrid.DataBind();
SetYourCachedData(data);
}
protected void btnSaveData_Click(object sender, EventArgs e)
{
// Pull data from the ViewState cache
List<YourData> data = GetYourCachedData();
// Now iterate through data to save it to your database...
// look this up if you don't know how as this is a lot more work.
}
looks like you just need to set the output object's datasource and bind it.
I.e.:
myGrid.datasource = myDataTable
myGrid.databind()
And as Kelsey says -- keep your datatable in scope.
a public dim right above your page_load would be easier, if you just want to try it out. Otherwise, the separate class approach is a good way to go.