Combobox in a Silverlight 3.0 dataform - silverlight-3.0

With the new release of Silverlight 3 and the move of the DataForm to the SilverLight Toolkit - does anyone know how to programatically add items to a combobox in a DataForm? There doesn't seem to be any of accessing it via the code file/
Thanks
~Steve

Yes, you can manage it by
dataForm.ContentLoaded += (sender, args) =>
{
TextBox myTextBox = (TextBox)dataForm.FindNameInContent("myTextBox");
// do something with the TextBox...
};
Look in here for details: http://silverlight.net/forums/t/108278.aspx

private void dataForm_ContentLoaded(object sender, DataFormContentLoadEventArgs e)
{
Dictionary<string, short> products= GetProducts();
foreach (string key in products.Keys)
{
ComboBoxItem listBoxItem = new ComboBoxItem();
ComboBox cmbProducts = (ComboBox)dataForm.FindNameInContent
("cmbProducts");
listBoxItem.Name = cmbProducts.Name + key;
listBoxItem.Content = key;
cmbProducts.Items.Add(listBoxItem);
}
}
On the XAML declare teh event for ur dataForm.

Related

The attribute android:onClick="FabOnClick" crashes app when Floating Action Button clicked

There doesn't appear to be a lot of people using Xamarin for Visual Studio consequently there isn't a lot of information specific to that platform out there.
Having said that, I've been trying to get a Floating Action Button (FAB) to work and it's been quite the exercise. I finally got it to appear and assign it to a variable in the activity with help from the nice folks who use StackOverflow, but cannot get the android:onClick="FabOnClick" call to work. Clicking on the FAB causes the app to crash with the error:
Unhandled Exception:
Java.Lang.IllegalStateException: Could not find method FabOnClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.design.widget.FloatingActionButton with id 'fab' occurred
This is the code in my activity:
public void FabOnClick(View v)
{
int x = 1;
}
It doesn't really do anything because I'm just trying to capture the click event for now. I set a breakpoint on the int x = 1 line to see when it's is executed. So what am I missing?
* Update *
I updated my activity code based on #Digitalsa1nt's answer below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Acr.UserDialogs;
using Android.Net;
using System.Net;
using Android.Support.Design.Widget;
using System.Threading.Tasks;
using Android.Views.InputMethods;
using static Android.Views.View;
namespace OML_Android
{
[Activity(Label = "CreateAccount")]
public class CreateAccount : Activity
{
public string result = "";
public EditText aTextboxUsername;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.CreateAccount);
RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
aTextboxUsername = FindViewById<EditText>(Resource.Id.aTextboxUsername);
EditText aTextboxPassword = FindViewById<EditText>(Resource.Id.aTextboxPassword);
EditText aTextboxPassword2 = FindViewById<EditText>(Resource.Id.aTextboxPassword2);
EditText txtEmailAddress = FindViewById<EditText>(Resource.Id.txtEmailAddress);
EditText txtEmailAddress2 = FindViewById<EditText>(Resource.Id.txtEmailAddress2);
EditText txtFirstName = FindViewById<EditText>(Resource.Id.first_name);
EditText txtMI = FindViewById<EditText>(Resource.Id.mi);
EditText txtLastName = FindViewById<EditText>(Resource.Id.last_name);
EditText txtAddress = FindViewById<EditText>(Resource.Id.address);
EditText txtCity = FindViewById<EditText>(Resource.Id.city);
Spinner spnState = FindViewById<Spinner>(Resource.Id.state);
EditText txtZip = FindViewById<EditText>(Resource.Id.zip);
MaskedEditText.MaskedEditText txtPhone = FindViewById<MaskedEditText.MaskedEditText>(Resource.Id.phone);
Spinner spnCompany = FindViewById<Spinner>(Resource.Id.company_spinner);
Spinner spnDept = FindViewById<Spinner>(Resource.Id.department_spinner);
Spinner spnSection = FindViewById<Spinner>(Resource.Id.section_spinner);
Button ButtonSubmit = FindViewById<Button>(Resource.Id.button_submit);
ScrollView sv = FindViewById<ScrollView>(Resource.Id.scrollView1);
ButtonSubmit.SetBackgroundColor(Android.Graphics.Color.YellowGreen);
// Hide the keyboard (also doesn't work)
InputMethodManager board = (InputMethodManager)GetSystemService(Context.InputMethodService);
board.HideSoftInputFromWindow(aTextboxUsername.WindowToken, 0);
// get the floating action button.
FloatingActionButton myFab = FindViewById< FloatingActionButton>(Resource.Id.fab);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
DataInterfaceWeb.DataInterface myService = new DataInterfaceWeb.DataInterface();
myFab.Click += FabButton_Click(); // <-- get error here
try
{
ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
bool isOnline = (activeConnection != null) && activeConnection.IsConnected;
if (!isOnline)
{
showMessage("There is no internet or cell phone connection. Connect to a network or connect to a cellular network.", "ERROR");
}
}
catch (Exception ex)
{
showMessage("Connectivity Manager failed to create a connection due to error: " + ex.Message, "ERROR");
};
// Create your application here
ButtonSubmit.Click += async (sender, e) =>
{
try
{
result = myService.CheckForUser(Master.username, Master.password, aTextboxUsername.Text);
if (result.ToUpper() == "Y")
{
await showMessage("Username " + aTextboxUsername.Text + " is already in use. Please choose another", "ERROR");
// aTextboxUsername.SetSelectAllOnFocus(true);
aTextboxUsername.RequestFocus();
View insideView = FindViewById<EditText>(Resource.Id.aTextboxUsername);
sv.ScrollTo(0, (int)insideView.GetY());
aTextboxUsername.SelectAll();
}
}
catch (Exception ex)
{
showMessage("Account creation attempt failed due to error: " + ex.Message, "ERROR");
}
};
}
public async Task showMessage(string message, string messageType)
{
var result = await UserDialogs.Instance.ConfirmAsync(new ConfirmConfig
{
Message = messageType + System.Environment.NewLine + message,
OkText = "Ok",
});
}
public void FabButton_Click()
{
int x = 1;
}
}
}
The error I get now is:
Cannot implicitly convert 'void' to 'SystemEventHandler' on the line myFab.Click += FabButton_Click();.
#Digitalsa1nt did point me in the right direction. Instead of
fabButton.Click += FabButton_Click;
I just wired up an event, as the error suggested (duh):
myFab.Click += (sender, e) =>
{
FabButton_Click();
};
It now works as I would expect.
So I'm making a couple of assumptions in this answer. Firstly that you are working with a Xamarin.Native project and not a Xamarin.Forms project.
Secondly I am assuming you are using the FloatingActionButton from one of the support libraries such as: Android.Support.Design.Widget (base / V4 / V7).
Once you've defined your FAB within the AXML Layout page:
<android.support.design.widget.FloatingActionButton
app:backgroundTint="#color/colourPrimary"
android:id="#+id/fabButton"
android:src="#drawable/image"
app:fabSize="normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:elevation="16dp"
android:translationZ="12dp"
app:rippleColor="#ffa9a9a9" />
You can get it from within your activity as such:
using Android.Support.Design.Widget;
// declare variable
private FloatingActionButton fabButton;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// call base
base.OnCreateView(inflater, container, savedInstanceState);
// inflate our view
var view = inflater.Inflate(Resource.Layout.MainTabWishlistPage, container, false);
// get our instance of the button using the resource ID.
fabButton = view.FindViewById<FloatingActionButton>(Resource.Id.fabButton);
// assign to click event
fabButton.Click += FabButton_Click;
}
private void FabButton_Click(object sender, EventArgs e)
{
int x = 1;
}
The above example is based on it being a fragment rather than an activity, but the methodology is the same.
Official Git Repo:
Xamarin/monodroid-samples - Floating Action Button Basic
Random online guide:
android-material-design-floating-action
In case this is a Xamarin.Forms project, look into James Montemagno's library (p.s one of the developers that works on Xamarin and creates tons of libraries to help make your life easier, definitely look through his other repos.)
jamesmontemagno/FloatingActionButton-for-Xamarin.Android

SqlDependency not working mvc app. Hits once

I am following the blog http://www.venkatbaggu.com/signalr-database-update-notifications-asp-net-mvc-usiing-sql-dependency/ to get a signalR push message out to connected clients.
My debugger never hits the onchange event.
my Global.asax.cs:
string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
protected void Application_Start()
{
// basic stuff
SqlDependency.Start(connString);
var repo = new Repositories.MarkerRepository();
repo.GetAllMarkers(); // to register the dependency
}
My MarkerRepository.cs:
readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
private MarkersHub _mh = new MarkersHub(); // my signalr hub class
public IEnumerable<House> GetAllMarkers()
{
var markers = new List<House>();
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(#"SELECT * FROM [dbo].Houses", connection))
{
command.Notification = null;
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
markers.Add(item: new House {
ID = (int)reader["ID"],
Name = (string)reader["Name"],
Code = reader["Code"] != DBNull.Value ? (string)reader["Code"] : "",
Latitude = Convert.ToDouble(reader["Latitude"]),
Longitude = Convert.ToDouble(reader["Longitude"])
});
}
}
}
return markers;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
_mh.SendMarkers();
}
}
I have had a hit once but it was no change, only a notification for subscribe. I have read a lot about resubscribe, but when it hit this event the sql:
select * from sys.dm_qn_subscriptions
still returns no rows. Not on my db or master. So I think that there is an error in the blog post with the re-subscribe to the on change event? This sample https://msdn.microsoft.com/en-us/library/a52dhwx7(VS.80).aspx does unregister in the onchange event and calls the method which registers a new event. Can someone verify my assumption?
These were the values for the SqlNotificationEventArgs e in my event and told me that my query to depend on, was invalid.
SqlNotificationEventArgs.Type --> SqlNotificationType.Subscribe
SqlNotificationEventArgs.Info --> SqlNotificationInfo.Invalid
SqlNotificationEventArgs.Source --> SqlNotificationSource.Statement
The statement may not use the asterisk () or table_name. syntax to specify columns.
source https://msdn.microsoft.com/en-us/library/ms181122.aspx

Multiselection of cells with muose and copy of TableView using JAVAFX

I have a TableView which is editable and multiple selection enabled. I wish to enter new data to some columns and rows. Then I wish to select using mouse and press CTRL-C to copy to clipboard.
I can use column.setCellFactory (TextFieldTableCell.forTableColumn ()); and my code works well for entering data like EXCEL. I could not select using mouse.
I read the reference How can I select multiple cells in tableview with javafx only by mouse?. If I try to implement it I need to use
final Callback<TableColumn<MyDataClass, String>, TableCell<MyDataClass, String>> myCellFactory = new DragSelectionCellFactory ();
column.setCellFactory (myCellFactory);.
Then I am unable to enter any data as CellFactory is different now..
How may I enter data like EXCEL and also select mouse and use CTRL-C to copy? Thanks for any help.
You can refactor the code in the link you provided so that it references another cell factory, and "decorates" the cells with the dragging functionality:
public class DragSelectionCellFactory<S,T> implements Callback<TableColumn<S,T>, TableCell<S,T>> {
private final Callback<TableColumn<S,T>, TableCell<S,T>> factory ;
public DragSelectionCellFactory(Callback<TableColumn<S,T>, TableCell<S,T>> factory) {
this.factory = factory ;
}
public DragSelectionCellFactory() {
this(col -> new TableCell<S,T>() {
#Override
protected void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
} else {
setText(item.toString());
}
}
});
}
#Override
public TableCell<S,T> call(final TableColumn<S,T> col) {
TableCell<S,T> cell = factory.call(col);
cell.setOnDragDetected(event -> {
cell.startFullDrag();
col.getTableView().getSelectionModel().select(cell.getIndex(), col);
});
cell.setOnMouseDragEntered(event -> {
col.getTableView().getSelectionModel().select(cell.getIndex(), col);
});
return cell ;
}
}
Then you can do
TableColumn<Person, String> column = ...
column.setCellFactory(
new DragSelectionCellFactory<Person, String>(TextFieldTableCell.forTableColumn()));

Capture Tab Click Event in Mono

I have a Tabhost in my app with 3 tabs. The tabs are all working fine.
Now I want to perform some additional logic when the tab is selected?.
For Example: In one of my tabs, I provide an option for the user to sort things in different order and update the another tab.
how can we get the click event of TabHost?
I have updated the Tab Creation (Activity) part.
Thanks in Advance.
[Activity(Label = "My Activity")]
public class TabSearch : TabActivity
{
protected override void OnCreate(Bundle bundle)
{
try
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Search_WOTab);
/* ******************** Adding 2 Tab Controls and setting Activity classes to Tabs added ******************** */
TabHost.TabSpec tspec;
Intent intent;
intent = new Intent(this, typeof(WOSearch));
intent.AddFlags(ActivityFlags.NewTask);
tspec = TabHost.NewTabSpec("Search");
tspec.SetIndicator("Search", Resources.GetDrawable(Resource.Drawable.Search));
tspec.SetContent(intent);
TabHost.AddTab(tspec);
intent = new Intent(this, typeof(WOFilter));
intent.AddFlags(ActivityFlags.NewTask);
tspec = TabHost.NewTabSpec("Filter");
tspec.SetIndicator("Filter", Resources.GetDrawable(Resource.Drawable.Filter));
tspec.SetContent(intent);
TabHost.AddTab(tspec);
TabHost.TabChanged += (sender, e) =>
{
Toast.MakeText(this, TabHost.CurrentTab.ToString(), ToastLength.Short).Show();
};
}
catch (Exception ex)
{
Toast.MakeText(this, ex.InnerException.ToString(), ToastLength.Short);
}
}
You can use the TabHost.TabChanged event.
tabHost.TabChanged += (sender, e) => {
if (tabHost.CurrentTab == 0) {
// Do what you want.
}
};
PS: Xamarin Docs is your friend.
Edit:
You should modify your code to this...
//TabHost.TabChanged += TabHost_TabChanged;
TabHost.TabChanged += (sender, e) =>
{
Toast.MakeText(this, TabHost.CurrentTab.ToString(), ToastLength.Short).Show();
};
TabHost.CurrentTab is the index of the selected tab.

I Want to display a listview when i click a button in Monodroid. i tried this coding. its not running. Can anyone correct this

I want to display a listview when I click a button in Monodroid. I tried the following code, however it doesn't run. Can anyone correct this?
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
Button button1 = FindViewById<Button> (Resource.Id.btn);
button1.Click += delegate { listviewFunction(); };
}
public void listviewFunction()
{
ListAdapter = new ArrayAdapter<string>(this, Resource.Layout.list_item, _countries);
ListView.TextFilterEnabled = true;
ListView.ItemClick += (sender, args) => Toast.MakeText(Application, ((TextView) args.View).Text, ToastLength.Short).Show();
}
Try just:
button1.Click += ...
Declare a ListView globally:
private ListView _listView;
Now (1)create the ListView, OR (2)get it from a axml file:
(1)
_listView = new ListView(this);
(2)
_listView = (ListView)View.FindViewById(Resource.Id.MyList);
Now create your adapter, then:
_listView.SetAdapter(myAdapter);
Then create your ItemClick handler:
_listView.ItemClick += (sender, args) => Toast.MakeText(Application, ((TextView) args.View).Text, ToastLength.Short).Show();

Resources