Hello this is the first time using Xamarin. What I am trying to do is modify this application to use ListView, but first I would like to learn how to get a value from a stepper and print it to the label.
I know movieamount sends the value selected from the stepper and sends it to the totalLabel text, but I can't seem to figure out how to send it to the label with 0 already and have it change values when selected. It does return the correct amount selected but never prints to the screen.
public static string movieamount;
public static string pickmovie;
public static string paymentSelected;
public static string dateSelected;
public static string timeSelected;
public static string totalLabel;
public MainPage()
{
Picker picker = new Picker
{
Title = "Movies",
VerticalOptions = LayoutOptions.CenterAndExpand
};
var options = new List<string> { "Kill Bill", "Matrix", "Zombieland", "The Dark Knight", "Terminator", "Apocalypse Now", "Resouvoir dogs", "Horrible Bosses", "The Breakup", "Wedding Crashers", };
picker.SelectedIndexChanged += (sender, e) =>
{
pickmovie = picker.Items[picker.SelectedIndex];
};
foreach (string optionName in options) picker.Items.Add(optionName);
//listView.ItemTapped += async (sender, e) => { await DisplayAlert("Tapped", e.Item.ToString() + " was selected.", "OK"); ((ListView)sender).SelectedItem = null; };
//this.Content = listView;
Label valuelabel = new Label
{
Text = "0",
FontAttributes = FontAttributes.Bold,
FontSize = 30,
HorizontalOptions = LayoutOptions.Center
};
Stepper stepper = new Stepper
{
Minimum = 0,
Maximum = 10,
Increment = 1,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.CenterAndExpand
};
stepper.ValueChanged += (sender, e)=>
{
movieamount = stepper.Value.ToString();
};
Picker payment = new Picker
{
Title = "Payment Method",
VerticalOptions = LayoutOptions.CenterAndExpand
};
var options1 = new List<string> {"Visa", "MasterCard", "AmericanExpress", "Free",};
foreach (string optionName in options1) payment.Items.Add(optionName);
payment.SelectedIndexChanged += (sender, e) =>
{
paymentSelected = payment.Items[payment.SelectedIndex];
};
//TimePicker was here
Label totalLabel = new Label
{
HorizontalOptions = LayoutOptions.CenterAndExpand,
FontSize = 40,
FontAttributes = FontAttributes.Bold | FontAttributes.Italic
};
DatePicker datePicker = new DatePicker
{
Format = "D",
VerticalOptions = LayoutOptions.CenterAndExpand,
};
//---Handle Inline---
datePicker.DateSelected += (object sender, DateChangedEventArgs e) =>
{
//eventValue.Text = e.NewDate.ToString();
dateSelected = e.NewDate.ToString();
};
TimePicker timePicker = new TimePicker
{
Format = "T",
VerticalOptions = LayoutOptions.CenterAndExpand
};
// set inline handler
timePicker.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == TimePicker.TimeProperty.PropertyName)
{
timeSelected = timePicker.Time.ToString();
};
};
Button button = new Button
{
Text = "Submit",
FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Button)),
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.Fill
};
button.Clicked += (sender, args) =>
{
totalLabel.Text = "You have ordered " + movieamount + " " +
pickmovie + " \n You will be paying with " + paymentSelected + " " +
"Your delivery will be delivered at " + dateSelected + " " + timeSelected;
};
StackLayout stackLayout = new StackLayout
{
Children =
{
picker,
payment,
valuelabel,
stepper,
datePicker,
totalLabel,
timePicker,
button,
}
};
BackgroundColor = Color.Yellow;
this.Content = stackLayout;
}
}
}
This is one way to approach it - a "brute force" method. Optionally, you could use MVVM and databinding, but that is more advanced and may be more than you want to bite off at this point
// declare this method outside of the constructor
private void UpdateLabel() {
totalLabel.Text = "You have ordered " + movieamount + " " +
pickmovie + " \n You will be paying with " + paymentSelected + " " +
"Your delivery will be delivered at " + dateSelected + " " +
timeSelected;
}
// then modify these existing handlers to call UpdateLabel
stepper.ValueChanged += (sender, e)=>
{
movieamount = stepper.Value.ToString();
UpdateLabel();
};
// you should also call UpdateLabel in the other handlers that update values
button.Clicked += (sender, args) =>
{
UpdateLabel();
};
ok. I will try that and expirement with it. I was able to find my answer with this line of code. That I entered right after stepper.ValueChanged += (sender, e)=>
valuelabel.Text = String.Format(" {0:F1}", e.NewValue);
Related
I've made a void method that adds pages to my tabbed page. In this, it creates entry boxes but they are unnamed. After the person has filled in the entry boxes I want to create a report from it. How do I access the entry boxes for the information?
This is the part that adds the new entry:
grid.Children.Add(new Entry
{
AutomationId = "weerstand" + lusnummer.ToString(),
Text = "[weerstand]",
TextColor = Color.Black,
FontSize = 18,
}, 2, rownumber);
//button and bottom
Button Reportbutton = new Button
{
Text = "Report",
BackgroundColor = Color.FromHex("#093d80"),
Padding = 24,
TextColor = Color.White,
FontSize = 36,
TextTransform = TextTransform.None,
};
Reportbutton.Clicked += GenerateReport_OnClicked;
grid2.Children.Add(
Reportbutton, 0, 0);
//make page
StackLayout stacklayout1 = new StackLayout()
{
Children =
{
grid,
grid2
}
};
ScrollView pagescroll = new ScrollView()
{
Content = stacklayout1
};
ContentPage page = new ContentPage()
{
Title = "LDTB-" + number.ToString(),
Content = pagescroll
};
Children.Add(page);
}
private async void GenerateReport_OnClicked(object sender, EventArgs e)
{
//yes or no
bool answer = await DisplayAlert("Rapport", "Wilt u het rapport maken", "Yes", "No");
//Generate report
if (answer == true){
//WHAT GOES HERE TO ACCESS THE Entry?
}
}
}
You can traverse your Grid and access the value of entries in it.
You can refer the following code:
var children = grid.Children;
foreach(View child in children){
if (child is Entry) {
string value = ((Entry)child).Text;
System.Diagnostics.Debug.WriteLine("one value is = " + value);
}
}
I'm making a journal application for myself in c# where i can make journals with dates attached to it.
I'm using a foreach statement to let the data display in the textboxes. I can't figure out how to display the journals in order (old->new) with the dates in Textbox3 (t3). I live in Europe so It's DD/MM/YYYY. I hope it's clear, thanks.
string[] journalfolder = Directory.GetDirectories(#"D:\panel\Journal\", "*");
foreach (string file in journalfolder)
{
Color grey = new Color();
TextBox t1 = new TextBox();
t1.Name = "t1_" + (t1.Controls.Count + 1);
t1.Location = new Point(265, 20);
grey = Color.FromArgb(31, 31, 31);
t1.Width = 332;
t1.BackColor = grey;
t1.BorderStyle = BorderStyle.None;
t1.ForeColor = Color.White;
try
{
string[] lines = File.ReadAllLines(file + #"\text.txt");
t1.Text = lines[0];
}
catch { }
TextBox t2 = new TextBox();
t2.Name = "t2_" + (t2.Controls.Count + 1);
t2.Location = new Point(265, 39);
t2.Width = 332;
t2.Height = 155;
grey = Color.FromArgb(31,31,31);
t2.BackColor = grey;
t2.Multiline = true;
t2.BorderStyle = BorderStyle.None;
t2.ForeColor = Color.White;
try
{
using (var sr = new StreamReader(file + #"\text.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
t2.Text = line;
}
}
}
catch { }
TextBox t3 = new TextBox();
t3.Name = "t3_" + (t3.Controls.Count + 1);
t3.Location = new Point(265, 199);
grey = Color.FromArgb(31, 31, 31);
t3.Width = 332;
t3.BackColor = grey;
t3.BorderStyle = BorderStyle.None;
t3.ForeColor = Color.White;
try
{
string[] lines = File.ReadAllLines(file + #"\date.txt");
t3.Text = lines[0];
}
catch { }
Panel image = new Panel();
image.Name = "image" + (image.Controls.Count + 1);
image.Location = new Point(20, 20);
image.BackgroundImageLayout = ImageLayout.Zoom;
image.Width = 223;
image.Width = 192;
try
{
string supportedExtensions = "*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg,*.wmf,*.ico,*.eps,*.tif,*.tiff";
foreach (string imageFile in Directory.GetFiles(file + #"\Files", "*.*", SearchOption.AllDirectories).Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower())))
{
Console.WriteLine(imageFile);
image.BackgroundImage = Image.FromFile(imageFile);
}
}
catch { }
Panel p = new Panel();
p.Name = "panel" + (flowLayoutPanel1.Controls.Count + 1);
p.BackColor = Color.FromArgb(49,49,49);
p.Width = 628;
p.Height = 236;
p.Controls.Add(t1);
p.Controls.Add(t2);
p.Controls.Add(t3);
p.Controls.Add(image);
flowLayoutPanel1.Controls.Add(p);
}
I'm not quite sure I understand your requirement correctly, but I'll give it a try ...
The date is managed in a date.txt file. It contains the date in the format DD/MM/YYYY, correct?
DateTime timestamp = DateTime.Parse("ValueFromFile");
It is best to put the title, text and date in a class or struct. Maybe something like this:
public class Data
{
public string Title { get; set; }
public string Text { get; set; }
public DateTime Timestamp { get; set; }
}
You should put all the elements you have read into a list or a dictionary before displaying them on the UI and processing them further. Once all the data is in this list, you can easily sort it by date using LINQ.
List<Data> values = new List<Data>();
// TODO
// Add the items
foreach (Data item in values.OrderBy((item) => item.Timestamp))
{
}
// Or
foreach (Data item in values.OrderByDescending((item) => item.Timestamp))
{
}
I want to add some panel dynamically into a single panel on a button click. And each dynamic panel consist of multiple text box in horizontally. And then I want to save those text box value into the database.
I have completed to add dynamic panel and horizontal multiple text box into that panel. But couldn't know how to save them into database.
Here is the code I have written:
int v = 0;
TextBox txt1;
TextBox txt2;
TextBox txt3;
TextBox txt4;
TextBox txt5;
ComboBox cmb4;
public void tett()
{
v = 0;
Panel whitePanel = new Panel();
whitePanel.Name = "wt";
// Quantity
txt1 = new TextBox();
txt1.Location = new Point(192, 38);
txt1.Size = new Size(120, 24);
txt1.Name = "text" + v ;
txt1.Text = txt1.Name;
v = v + 1;
// Total Price
txt2 = new TextBox();
txt2.Location = new Point(566, 38);
txt2.Size = new Size(120, 24);
txt2.Name = "text" + v;
txt2.Text = txt2.Name;
txt2.TextChanged += Txt2_TextChanged;
v = v + 1;
// Unit Price
txt3 = new TextBox();
txt3.Location = new Point(753, 38);
txt3.Size = new Size(120, 24);
txt3.Name = "text" + v;
txt3.Text = txt3.Name;
v = v + 1;
// Sell Price
txt4 = new TextBox();
txt4.Location = new Point(903, 38);
txt4.Size = new Size(120, 24);
txt4.Name = "text" + v;
txt4.Text = txt4.Name;
v = v + 1;
// Product
txt5 = new TextBox();
txt5.Location = new Point(5, 38);
txt5.Size = new Size(120, 24);
txt5.Name = "text" + v;
txt5.Text = txt5.Name;
txt5.AutoCompleteSource = AutoCompleteSource.CustomSource;
txt5.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txt5.MouseClick += textBox5_MouseClick;
Label lbl3 = new Label();
Label lbl4 = new Label();
Label lbl5 = new Label();
Label lbl6 = new Label();
Label lbl7 = new Label();
Label lbl8 = new Label();
lbl3.Location = new Point(5, 15);
lbl3.Text = "Product";
lbl4.Location = new Point(192, 15);
lbl4.Text = "Quantity";
lbl5.Location = new Point(379, 15);
lbl5.Text = "Unit";
lbl6.Location = new Point(566, 15);
lbl6.Text = "Total Price";
lbl7.Location = new Point(753, 15);
lbl7.Text = "Unit Purchase Price";
lbl8.Location = new Point(903, 15);
lbl8.Text = "Unit Sell Price";
cmb4 = new ComboBox();
// Unit
cmb4.Location = new Point(379, 38);
cmb4.Size = new Size(120, 24);
whitePanel.BackColor = ColorTranslator.FromHtml("#ECF0F5");
whitePanel.Location = new Point(1, a * 10);
whitePanel.Size = new Size(1330, 60);
var _button = new Button();
_button.Text = "Dispose";
_button.Name = "DisposeButton";
_button.Location = new Point(1053, 38);
_button.MouseClick += _button_MouseClick;
whitePanel.Controls.Add(_button);
a = a + 5;
v = v + 1;
whitePanel.Controls.Add(lbl3);
whitePanel.Controls.Add(lbl4);
whitePanel.Controls.Add(lbl5);
whitePanel.Controls.Add(lbl6);
whitePanel.Controls.Add(lbl7);
whitePanel.Controls.Add(lbl8);
whitePanel.Controls.Add(txt1);
whitePanel.Controls.Add(txt2);
whitePanel.Controls.Add(txt3);
whitePanel.Controls.Add(txt4);
whitePanel.Controls.Add(txt5);
whitePanel.Controls.Add(cmb4);
panel1.Controls.Add(whitePanel);
}
In this way the output is like this..... By click on the New Purchase this multiple panel with text box will appear:
Multiple dynamic panel with multiple text box
Here the way of setting text box name is not seems better way to me. I want to use an array for set the name of text boxes.
And after all I want to save those values into db by click on the save button using an array or for loop... But I don't know how to define it..
Can anyone please help me?
And thanks in advance
With this approach, a gridview is usefull.
But within your question, the approach is;
int rowNum = 1;
public void tett() {
Control[] controlsToAdd = { new TextBox(), new TextBox(), new ComboBox(), new TextBox(), new TextBox(), new TextBox(), new Button() };
string[] labels = { "Product", "Quantity", "Unit", "Total Price", "Unit Purchase", "Unit Sell Price" };
Panel whitePanel = new Panel() {
Name = "wt",
Dock = DockStyle.Top,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
AutoSize = true,
Padding = new Padding(0, 5, 0, 5),
BackColor = ColorTranslator.FromHtml("#ECF0F5")
};
int controlX = 5, controlY = 15, controlDistance = 15;
for (int i = 0; i < controlsToAdd.Length; i++) {
if (labels.Length > i) {
var label = new Label() {
Text = labels[i],
Location = new Point(controlX, controlY)
};
whitePanel.Controls.Add(label);
}
var control = controlsToAdd[i];
control.Location = new Point(controlX, controlY + 23);
control.Size = new Size(120, 24);
if (control is Button) {
control.Name = "disposeButton" + i;
control.Text = "Dispose";
control.Click += _button_MouseClick;
} else {
if(i == 0) { //if it is the Product textbox
((TextBox)control).AutoCompleteSource = AutoCompleteSource.CustomSource;
((TextBox)control).AutoCompleteMode = AutoCompleteMode.SuggestAppend;
//control.MouseClick += textBox5_MouseClick;
}
control.Name = "Text" + i;
control.Text = "Row" + rowNum + " Text" + i;
}
whitePanel.Controls.Add(control);
controlX += 120 + controlDistance;
}
panel1.Controls.Add(whitePanel);
whitePanel.BringToFront();
rowNum++;
}
private void _button_MouseClick(object sender, EventArgs e) {
//button does its job here
((Button)sender).Parent.Parent.Controls.Remove(((Button)sender).Parent);
}
public SqlConnection Conn { get; }
void save() {
foreach(Panel whitePanel in panel1.Controls) {
var sqlString = "INSERT INTO products(productField, quantityField, unitField, priceField, purchaseField, sellPriceField) VALUES (";
foreach (Control control in whitePanel.Controls) {
if(!(control is Label) && !(control is Button)) { //So, textbox or combobox remained
sqlString += "'"+ control.Text +"', ";
}
}
sqlString = sqlString.Substring(0, sqlString.Length - 2) + ")";
//Assume you have previous construction of SqlConnection as name "Conn"
if (Conn != null) {
if (Conn.State != ConnectionState.Open) Conn.Open();
using (var cmd = new SqlCommand(sqlString, Conn)) {
cmd.ExecuteNonQuery();
}
Conn.Close();
}
Console.WriteLine(sqlString);
}
}
I have tested and works as expected. If it is not suit your needs, make me know.
I have a PivotGrid (DevExpress) within WPF and bind the DataSource to an IList that contains objects of which there are several properties of type DateTime. I want the end-user to choose during runtime which of those DateTime fields the user wants to group by Year, Month, or Day. Is that possible?
I understand that I can provide DateTime groupings programmatically but as there are several DateTime fields it would be quite tedious and unnecessary if the end-user can choose which DateTime field to group and how to group it during runtime.
Can you please guide me how to do that?
I have the following:
<dxdo:LayoutControlItem ItemWidth="1*">
<dxpg:PivotGridControl MaxHeight="800" MaxWidth="800" DataSource="{Binding AllChildOrders}" DataSourceChanged="PivotGridControl_OnDataSourceChanged">
</dxpg:PivotGridControl>
</dxdo:LayoutControlItem>
and in code behind:
private void PivotGridControl_OnDataSourceChanged(object sender, RoutedEventArgs e)
{
var pivotTable = sender as PivotGridControl;
pivotTable.RetrieveFields();
}
The above code works and the pivot table displays all available fields during runtime, including the fields of type DateTime. I do not want to programmatically specify which fields to group in particular ways but let the end-user during runtime choose how and which field to group. Possible?
Alternatively I could imagine to programmatically create sub-groupings as follows: How can I accomplish the following?
0. Pre-generate groups
If you don't want to programmatically specify which fields to group, then you can pregenerate groups for each DateTime field, so user can choose between fields itself and groups of fields.
Here is example:
private void PivotGridControl_DataSourceChanged(object sender, RoutedEventArgs e)
{
var pivotTable = sender as PivotGridControl;
pivotTable.Groups.Clear();
pivotTable.RetrieveFields();
var dateTimeFields = pivotTable.Fields.Where(item => item.DataType == typeof(DateTime)).ToList();
foreach (var field in dateTimeFields)
{
var group = new PivotGridGroup();
group.Add(new PivotGridField() { FieldName = field.FieldName, Caption = field.Caption + " (year)", GroupInterval = FieldGroupInterval.DateYear });
group.Add(new PivotGridField() { FieldName = field.FieldName, Caption = field.Caption + " (month)", GroupInterval = FieldGroupInterval.DateMonth });
group.Add(new PivotGridField() { FieldName = field.FieldName, Caption = field.Caption + " (day)", GroupInterval = FieldGroupInterval.DateDay });
foreach (var groupField in group)
pivotTable.Fields.Add(groupField);
pivotTable.Groups.Add(group);
}
}
Here is screenshot of example:
1. Create sub-groupins
You can create sub-groupings by using PivotGridField.DisplayFolder property.
Here is example:
private void PivotGridControl_DataSourceChanged(object sender, RoutedEventArgs e)
{
var pivotTable = sender as PivotGridControl;
pivotTable.RetrieveFields();
var dateTimeFields = pivotTable.Fields.Where(item => item.DataType == typeof(DateTime)).ToList();
foreach (var field in dateTimeFields)
{
var fieldYear = new PivotGridField()
{
FieldName = field.FieldName,
Caption = field.Caption + " (year)",
GroupInterval = FieldGroupInterval.DateYear,
Visible = false,
DisplayFolder = field.Caption
};
var fieldMonth = new PivotGridField()
{
FieldName = field.FieldName,
Caption = field.Caption + " (month)",
GroupInterval = FieldGroupInterval.DateMonth,
Visible = false,
DisplayFolder = field.Caption
};
var fieldDay = new PivotGridField()
{
FieldName = field.FieldName,
Caption = field.Caption + " (day)",
GroupInterval = FieldGroupInterval.DateDay,
Visible = false,
DisplayFolder = field.Caption
};
pivotTable.Fields.Add(fieldYear);
pivotTable.Fields.Add(fieldMonth);
pivotTable.Fields.Add(fieldDay);
}
}
Here is result:
2. Customize popup menu
You can add commands to field popup menu which allows user to change group interval. For this you can use PivotGridControl.PopupMenuShowing event and PopupMenuShowingEventArgs.Customizations property to customize menu.
Here is example:
private void PivotGridControl_DataSourceChanged(object sender, RoutedEventArgs e)
{
var pivotTable = sender as PivotGridControl;
pivotTable.Groups.Clear();
pivotTable.RetrieveFields();
}
private void PivotGridControl_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
{
if (e.MenuType != PivotGridMenuType.Header)
return;
var fieldHeader = e.TargetElement as FieldHeader;
if (fieldHeader == null)
return;
var field = fieldHeader.Content as PivotGridField;
if (field == null || (field.Group != null && field.Group.IndexOf(field) > 0))
return;
var groupInterval = field.GroupInterval;
if (groupInterval == FieldGroupInterval.Default && field.DataType != typeof(DateTime))
return;
var dateTimeIntervals = new List<FieldGroupInterval>(new FieldGroupInterval[]
{
FieldGroupInterval.DateYear,
FieldGroupInterval.DateQuarter,
FieldGroupInterval.DateMonth,
FieldGroupInterval.DateDay,
FieldGroupInterval.Hour,
FieldGroupInterval.Minute,
FieldGroupInterval.Second,
FieldGroupInterval.DateWeekOfYear,
FieldGroupInterval.DateWeekOfMonth,
FieldGroupInterval.DateDayOfYear,
FieldGroupInterval.DateDayOfWeek,
FieldGroupInterval.Date,
FieldGroupInterval.Default
});
if (!dateTimeIntervals.Contains(groupInterval))
return;
var pivotTable = sender as PivotGridControl;
var subMenu = new BarSubItem() { };
subMenu.Content = "Set group interval";
if (field.Group == null)
{
var button = new BarButtonItem() { Content = "Year - Month - Date" };
button.ItemClick += (s, eventArgs) =>
{
pivotTable.BeginUpdate();
var group = field.Tag as PivotGridGroup;
if (group == null)
{
if (groupInterval != FieldGroupInterval.Default)
field.Caption = field.Caption.Replace(" (" + groupInterval + ")", string.Empty);
group = new PivotGridGroup();
group.Add(new PivotGridField() { FieldName = field.FieldName, Caption = field.Caption + " (year)", GroupInterval = FieldGroupInterval.DateYear, Tag = field, Area = field.Area, AreaIndex = field.AreaIndex });
group.Add(new PivotGridField() { FieldName = field.FieldName, Caption = field.Caption + " (month)", GroupInterval = FieldGroupInterval.DateMonth });
group.Add(new PivotGridField() { FieldName = field.FieldName, Caption = field.Caption + " (day)", GroupInterval = FieldGroupInterval.DateDay });
foreach (var groupField in group)
pivotTable.Fields.Add(groupField);
pivotTable.Groups.Add(group);
group.Tag = field;
}
else
{
var yearField = group[0];
yearField.Area = field.Area;
yearField.AreaIndex = field.AreaIndex;
yearField.ShowInCustomizationForm = true;
}
field.Visible = false;
field.ShowInCustomizationForm = false;
pivotTable.EndUpdate();
};
subMenu.Items.Add(button);
}
foreach (var dateTimeInterval in dateTimeIntervals.Where(item => item != groupInterval))
{
var button = new BarButtonItem() { Content = dateTimeInterval, Tag = field };
subMenu.Items.Add(button);
button.ItemClick += (s, eventArgs) =>
{
pivotTable.BeginUpdate();
var group = field.Group;
if (group != null)
{
var yearField = field;
field = yearField.Tag as PivotGridField;
field.Area = yearField.Area;
field.AreaIndex = yearField.AreaIndex;
field.ShowInCustomizationForm = true;
yearField.Visible = false;
yearField.ShowInCustomizationForm = false;
}
else if (groupInterval != FieldGroupInterval.Default)
field.Caption = field.Caption.Replace(" (" + groupInterval + ")", string.Empty);
field.GroupInterval = dateTimeInterval;
if (dateTimeInterval != FieldGroupInterval.Default)
field.Caption += " (" + dateTimeInterval + ")";
pivotTable.EndUpdate();
};
}
e.Customizations.Add(subMenu);
}
Here is result:
I have to update my txtid , txtName ,txtAge ,txtContact..OnSelectionChange of ListPicker , but even after selecting items it is not updating txtfields . How can i step up on it ?
public partial class Update : PhoneApplicationPage
{
Button btnUpdate1 = null;
TextBox txtid = null;
TextBox txtName = null;
TextBox txtAge = null;
TextBox txtContact = null;
ListPicker lp = null;
int selectedItem ;
public Update()
{
InitializeComponent();
int x = noofrows();
createUpdateButton();
createListPicker();
selectedItem = Convert.ToInt32(lp.SelectedItem);
createTxtId(selectedItem);
createTxtName(selectedItem);
createTxtAge(selectedItem);
createTxtContact(selectedItem);
}
public void createListPicker()
{
lp = new ListPicker();
lp.BorderBrush = new SolidColorBrush(Colors.White);
lp.BorderThickness = new Thickness(3);
lp.Margin = new Thickness(12, 5, 0, 0);
lp.Width = 400;
int x = noofrows();
for (int a = 1; a <= x; a++)
{
string str1 = returnID(a);
lp.Items.Add(str1);
}
lp.SelectionChanged += (s, e) =>
{
selectedItem = Convert.ToInt32(lp.SelectedItem);
};
LayoutRoot.Children.Add(lp);
}
public void createUpdateButton()
{
btnUpdate1 = new Button();
btnUpdate1.Margin = new Thickness(100, 600, 0, 0);
btnUpdate1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
btnUpdate1.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
btnUpdate1.Height = 100;
btnUpdate1.Width = 150;
btnUpdate1.Content = "update";
btnUpdate1.Foreground = new SolidColorBrush(Colors.White);
btnUpdate1.Background = new SolidColorBrush(Colors.Black);
btnUpdate1.BorderBrush = new SolidColorBrush(Colors.White);
btnUpdate1.BorderThickness = new Thickness(3);
btnUpdate1.FontSize = 28;
LayoutRoot.Children.Add(btnUpdate1);
btnUpdate1.Click += (s, e) =>
{
UpdateDatabase(selectedItem);
};
}
public void createTxtId(int z)
{
int id = z ;
txtid = new TextBox();
txtid.Margin = new Thickness(12, 100, 0, 0);
txtid.Width = 400;
txtid.Height = 100;
txtid.FontSize = 28;
txtid.Foreground = new SolidColorBrush(Colors.Black);
txtid.BorderBrush = new SolidColorBrush(Colors.Black);
txtid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtid.BorderThickness = new Thickness(3);
txtid.IsReadOnly = true;
txtid.Text = " " + id;
LayoutRoot.Children.Add(txtid);
}
public void createTxtName(int z)
{
txtName = new TextBox();
txtName.Margin = new Thickness(12, 200, 0, 0);
txtName.Width = 400;
txtName.Height = 100;
txtName.FontSize = 28;
txtName.Foreground = new SolidColorBrush(Colors.Black);
txtName.BorderBrush = new SolidColorBrush(Colors.Black);
txtName.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtName.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtName.BorderThickness = new Thickness(3);
txtName.Text = SelectName(z);
txtName.Tap += (s, e) =>
{
if (txtName.Text == "Name")
{
txtName.Text = "";
}
};
txtName.LostFocus += (s, e) =>
{
if (txtName.Text == "")
{
txtName.Text = "Name";
}
};
LayoutRoot.Children.Add(txtName);
}
public void createTxtAge(int z)
{
txtAge = new TextBox();
txtAge.Margin = new Thickness(12, 300, 0, 0);
txtAge.Width = 400;
txtAge.Height = 100;
txtAge.FontSize = 28;
txtAge.Foreground = new SolidColorBrush(Colors.Black);
txtAge.BorderBrush = new SolidColorBrush(Colors.Black);
txtAge.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtAge.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtAge.BorderThickness = new Thickness(3);
txtAge.MaxLength = 2;
txtAge.Text = SelectAge(z);
txtAge.InputScope = new InputScope();
txtAge.InputScope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.Number });
txtAge.Tap += (s, e) =>
{
if (txtAge.Text == "Age")
{
txtAge.Text = "";
}
};
txtAge.LostFocus += (s, e) =>
{
if (txtAge.Text == "")
{
txtAge.Text = "Age";
}
};
LayoutRoot.Children.Add(txtAge);
}
public void createTxtContact(int z)
{
txtContact = new TextBox();
txtContact.Margin = new Thickness(12, 400, 0, 0);
txtContact.Width = 400;
txtContact.Height = 100;
txtContact.FontSize = 28;
txtContact.MaxLength = 10;
txtContact.Foreground = new SolidColorBrush(Colors.Black);
txtContact.BorderBrush = new SolidColorBrush(Colors.Black);
txtContact.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtContact.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtContact.BorderThickness = new Thickness(3);
txtContact.Text = SelectContact(z);
txtContact.InputScope = new InputScope();
txtContact.InputScope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.Number });
txtContact.Tap += (s, e) =>
{
if (txtContact.Text == "Contact")
{
txtContact.Text = "";
}
};
txtContact.LostFocus += (s, e) =>
{
if (txtContact.Text == "")
{
txtContact.Text = "Contact";
}
};
LayoutRoot.Children.Add(txtContact);
}
public Int32 noofrows()
{
int b = Convert.ToInt32((Application.Current as App).db.SelectList("select count(*) from details"));
return b;
}
public string returnID(int z)
{
return Convert.ToString((Application.Current as App).db.SelectList("select id from details where id =" + z));
}
public String SelectName(int x)
{
return Convert.ToString((Application.Current as App).db.SelectList("select name from details where id =" + x));
}
public String SelectAge(int x)
{
return Convert.ToString((Application.Current as App).db.SelectList("select age from details where id =" + x));
}
public String SelectContact(int x)
{
return Convert.ToString((Application.Current as App).db.SelectList("select contact from details where id =" + x));
}
public void UpdateDatabase(int ID)
{
if (txtName.Text=="Name")
{
MessageBox.Show("Enter a valid Name");
}
else if (txtAge.Text.Length>=3||txtAge.Text=="Age")
{
MessageBox.Show("Enter A valid Age (1-99)");
}
else if (txtContact.Text.Length != 10)
{
MessageBox.Show("Enter a valid Mobile number Of 10 digit");
}
else
{
string s1 = "update details set id='" + Convert.ToInt64(txtid.Text) + "', name = '" + txtName.Text + "', age = '" + txtAge.Text + "', contact = '" + txtContact.Text + "'where id = " + ID;
string s2 = Convert.ToString((Application.Current as App).db.SelectList(s1));
MessageBox.Show("Updated Successfully");
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
}
}
You are using so much code. Its would be better if you follow the MVM architecture and try to set Bind the textblocks to your viewModel. Lets consider the following scenario.
You have binded the xaml elements to selectedItem in your viewModel. Now when selectedItem's value is changed Notify event is triggered which will notify the UI and the values will automatically be updated.
I recommend you to study viewmodel and try to implement it. Its really easy and would save you a lot of hassle.
Try implementing some samples
Hope it helps :)
I got this ...
Actually if we want to update that we need to change text of each text box . So after the selection change , Try it like this.
public void createListPicker()
{
lp = new ListPicker();
lp.BorderBrush = new SolidColorBrush(Colors.White);
lp.BorderThickness = new Thickness(3);
lp.Margin = new Thickness(12, 5, 0, 0);
lp.Width = 400;
int x = noofrows();
for (int a = 1; a <= x; a++)
{
string str1 = returnID(a);
lp.Items.Add(str1);
}
lp.SelectionChanged += (s, e) =>
{
selectedItem = Convert.ToInt32(lp.SelectedItem);
txtid.Text = selectedItem.ToString();
txtName.Text = SelectName(selectedItem);
txtAge.Text = SelectAge(selectedItem);
txtContact.Text = SelectContact(selectedItem);
};
LayoutRoot.Children.Add(lp);
}
This will update Immediately after Every selection change Event .