rs = statement.executeQuery("select * from user");
while (rs.next()) {
String username = rs.getString("staffname");
options1.add(username); // ObservableList<String> options1 = FXCollections.observableArrayList();
}
cb.setItems(options1); // cb is ComboBox object
cb.setPromptText("Select Your Account");
cb.setPrefSize(280, 30);
Button bt = new Button("Sign In");
bt.setFont(Font.font("Calibri", FontWeight.NORMAL, 17));
bt.setStyle(" -fx-base: #333333;");
bt.setTextFill(Color.WHITE);
bt.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
try {
setCenter(userSignin());
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(FrontPage.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
This is my code to read some values from a database and display it in a ComboBox. Now I need to remove all the values in the ComboBox when the Button is pressed. I want to remove all at one click. How can I do it ?
cb.getItems().clear()
should remove everything in the ComboBox.
Edited: Corrected to call the right container. Sorry, used to the children in the panes.
I have tried. cb.getItems().removeAll(); But it is not worked properly. the right method to delete all data inside the comboBox is as follow
cb.getItems().clear();
cb- variable name of comboBox
Related
I have a DataGridView bound to a DataTable. I added a DataGridViewButtonColumn that serves as the delete button for the row.
Since it is bound to a DataTable, I'd like to be able to get the object of the row with the delete button clicked so I can delete it from the DataTable and then refresh the DataGrid.
This is how my button is setup:
var colDelete = new DataGridViewButtonColumn();
colDelete.Name = "DeleteButton";
colDelete.HeaderText = "Delete";
colDelete.Text = "Delete";
colDelete.UseColumnTextForButtonValue = true;
colDelete.DataPropertyName = "EthnicityDetailID";
colDelete.DisplayIndex = 10;
dataGridEthnicityData.Columns.Add(colDelete);
This is how I'm planning to handle the button click event:
private void dataGridEthnicityData_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
try
{
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.ColumnIndex == senderGrid.Columns["DeleteButton"].Index)
{
//ethnicityDataTable.Rows.RemoveAt(e.RowIndex);
dataGridEthnicityData.Refresh();
}
}
catch (Exception ex)
{
MessageBox.Show("Error deleting ethnicity data: " + ex.Message + " " + ex.StackTrace);
}
}
How do I assign EthnicityDetailID as the value for the button and how do I retrieve the row with the button clicked as an object so I can retrieve the value and delete accordingly in the datatable?
Thank you.
Apparently you have bound your DataTable to the DataSource of your DataGridView. If you have separated your Data from how the data is displayed, you will have code that is similar to:
BindingList<Ethnicity> DisplayedEthnicities
{
get => (BindingList<Ethnicity>) this.dataGridView1.DataSource,
set => this.dataGridView1.DataSource = value;
}
Ethnicity GetEthnicity(DataGridViewRow row)
{
return (Ethnicity)row.DataboundItem;
}
Ethnicity CurrentEthnicity => this.dataGridView1.CurrentCell?.OwnindRow as Ethnicity;
IEnumerable<Ethnicity> SelectedEthnicities => this.dataGridView1.SelectedRows
.Select(row => this.GetEthnicity(row));
You also need conversions between Datatable and Ethnicity:
void IEnumerable<Ethnicities> ToEthnicities(DataTable dataTable)
{
// TODO: convert the rows of the datatable into Ethnicities
}
You know better than I do how the ethnicities are in your datatable.
After this, filling the DataGridView will be easy:
DataTable CreateDataTable()
{
// TODO: fill the datatable with data from database? CSV file? Json?
}
void FillDataGridView()
{
var dataTable = this.CreateDataTable();
var ethnicities = this.ToEthnicities(dataTable);
this.DisplayedEthnicities = new BindingList<Enthnicity>(ethnicities.ToList());
}
I'd like to be able to get the object of the row with the delete button clicked
After you've done it like this, getting the databound item will be easy:
void OnCellContent_Clicked(object sender, DataGridViewCellEventArgs e)
{
DataGridViewRow row = this.DataGridView1.Rows[e.RowIndex];
Ethnicity ethnicity = this.GetEthnicity(row);
ProcessEthnicity(ethnicity);
}
I have a wpf application that has a datagrid with names in the first column and additional info in other columns. The names are in sorted order. If a user presses a key on the keyboard, say p, I would like the datagrid to go to the first row where the name begins with p. If the user then presses e, go to the first row that begins with pe, etc. Is this possible in a datagrid? I haven't been able to find anything or examples on this. Please help.
For that you should add keydown event.
And Step 1 : OnkeyDown event get text of key.
Step 2 : find item as per your condition from list.
Step 3 : Change selected item.
Step 4 : and scroll datagrid to selected item.
Window keydown event work correctly, in my case datagrid event worked when row was selected.
Here is code.
List<Employee> empData = new List<Employee>();
private Task task;
private CancellationToken token;
private CancellationTokenSource tokenSource;
private string searchText = "";
KeyDownEvent :
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (task != null && tokenSource != null)
{
// cancel task
tokenSource.Cancel();
tokenSource = null;
Console.WriteLine("Task cancel");
}
// Set condition for key
string txt = new KeyConverter().ConvertToString(e.Key);
if (txt.ToString().ToList().Any(x => !Char.IsLetterOrDigit(x)))
{
Console.WriteLine("Retrun from.");
return;
}
searchText = searchText + new KeyConverter().ConvertToString(e.Key);
Console.WriteLine("Search text : " + searchText);
var item = empData.FirstOrDefault(x=>x.FirstName.StartsWith(searchText));
if (item != null)
{
myGrid.SelectedItem = item;
myGrid.UpdateLayout();
myGrid.ScrollIntoView(myGrid.SelectedItem);
}
// create task for clean text
Console.WriteLine("Task generate");
tokenSource = new CancellationTokenSource();
token = tokenSource.Token;
task = new Task(()=> CleanSearchText(token), token);
task.Start();
}
Task for clean text after sometime
private void CleanSearchText(CancellationToken token)
{
// Throw if cancellation request
token.ThrowIfCancellationRequested();
// Wait for sometime for next key prss
Thread.Sleep(400);
// Do nothing if cancelation request
if (token.IsCancellationRequested)
{
return;
}
Console.WriteLine("Clean text");
searchText = "";
}
It is possible. A simple example for Datagrid:
http://www.wpf-tutorial.com/datagrid-control/details-row/
Then handle event keydown in Datagrid
<DataGrid Name="dgUsers" AutoGenerateColumns="False" KeyDown="DgUsers_OnKeyDown">
code behind simple:
private void DgUsers_OnKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
foreach (var row in dgUsers.Items)
{
User user = (User) row;
user.Name = e.Key.ToString();
dgUsers.SelectedItem = row;
break;
}
}
This is already built in!
<DataGrid IsTextSearchEnabled="True" ...
Now just let the models "ToString" method return the text you want to search for - done!
See also https://msdn.microsoft.com/en-us/library/system.windows.controls.textsearch.aspx
I am trying to change a label's text on the click of the button. So I change it using setText then I call revalidate() however when I run it and press the button, the text does not change in the label. here is my code.
What am I doing wrong???
public void setUpSignUpDialog() {
final Dialog signUpDialog = (Dialog) u.createContainer(theme, "SignUpDialog");
signUpDialog.setDisposeWhenPointerOutOfBounds(true);
signUpDialog.setTransitionInAnimator(CommonTransitions.createDialogPulsate());
signUpDialog.setTransitionOutAnimator(CommonTransitions.createDialogPulsate());
signUpDialog.showPacked(BorderLayout.CENTER, true);
final TextField emailField;
TextField passwordField;
TextField repeatPasswordField;
Button registerButton;
final Label errorLabel;
emailField = (TextField) u.findByName("EmailField", signUpDialog);
passwordField = (TextField) u.findByName("passwordField", signUpDialog);
repeatPasswordField = (TextField) u.findByName("RepeatPasswordField", signUpDialog);
registerButton = (Button) u.findByName("SignUpButton", signUpDialog);
errorLabel = (Label) u.findByName("ErrorLabel", signUpDialog);
registerButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
if (checkEmailField(emailField.getText())) {
} else {
errorLabel.setText("Please enter a valid email address");
errorLabel.getStyle().setFgColor(ColorUtil.CYAN);
signUpDialog.animate();
}
errorLabel.setText("Please enter a valid email address");
errorLabel.getStyle().setFgColor(ColorUtil.CYAN);
signUpDialog.revalidate();
}
});
}
Added the whole code of the signUpDialog. I added the code under the if statement just in case else wasn't being called. Still not working...
replace this code signUpDialog.showPacked(BorderLayout.CENTER, true);
with signupDilaog.show(); and it will work
public void setUpSignUpDialog() {
final Dialog signUpDialog = (Dialog) u.createContainer(theme, "SignUpDialog");
signUpDialog.setDisposeWhenPointerOutOfBounds(true);
signUpDialog.setTransitionInAnimator(CommonTransitions.createDialogPulsate());
signUpDialog.setTransitionOutAnimator(CommonTransitions.createDialogPulsate());
// signUpDialog.showPacked(BorderLayout.CENTER, true);
final TextField emailField;
TextField passwordField;
TextField repeatPasswordField;
Button registerButton;
final Label errorLabel;
emailField = (TextField) u.findByName("EmailField", signUpDialog);
passwordField = (TextField) u.findByName("passwordField", signUpDialog);
repeatPasswordField = (TextField) u.findByName("RepeatPasswordField", signUpDialog);
registerButton = (Button) u.findByName("SignUpButton", signUpDialog);
errorLabel = (Label) u.findByName("ErrorLabel", signUpDialog);
registerButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
if (checkEmailField(emailField.getText())) {
} else {
errorLabel.setText("Please enter a valid email address");
errorLabel.getStyle().setFgColor(ColorUtil.CYAN);
signUpDialog.animate();
}
errorLabel.setText("Please enter a valid email address");
errorLabel.getStyle().setFgColor(ColorUtil.CYAN);
signUpDialog.revalidate();
}
});
signUpDialog.show();
}
it should work
Is there any error message in output?
Can you post the whole codes of this signupDialog?
Check if the else part of that statement is actually called by printing some text in the log.
Try:
errorLabel.getParent().revalidate();
//OR
errorLabel.getParent().repaint();
I am using a win form to search the record and when the record is selected from a grid on celldoubleclick event. The search form should be closed and the selected row record is loaded back to to main form from which search form is begin called.
The code to open the search form.
private void F1Button_Click(object sender, EventArgs e)
{
Forms.frmSearchNewAccount frm = new Forms.frmSearchNewAccount();
frm.ShowDialog();
if (frm.DialogResult == System.Windows.Forms.DialogResult.OK)
{
//here comes the selected record
}
}
//Search Form grid view cell double click event code is here
try
{
if (e.RowIndex >= 0)
{
this._SelectedRecord = new Flour_Mills.PARTY();
_SelectedRecord.PARTY_ID = (string)((DataTable)SearchPartydataGrid.DataSource).Rows[e.RowIndex]["PARTY_ID"];
_SelectedRecord.NAME = (string)((DataTable)SearchPartydataGrid.DataSource).Rows[e.RowIndex]["NAME"];
Controller.PartyDAL.Load(_SelectedRecord.PARTY_ID);
DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The _selectedRecord is a static variable but it is not accessible in main form.
Any Suugestions????
If u need more explination I am here to to elaborate more.
Simply it can be do as:
public var _selectedRecordFromSearchForm;
private void F1Button_Click(object sender, EventArgs e)
{
Forms.frmSearchNewAccount frm = new Forms.frmSearchNewAccount();
frm.ShowDialog(this); // pass this form as Owner
if (frm.DialogResult == System.Windows.Forms.DialogResult.OK)
{
//here comes the selected record
}
}
In search form:
this._SelectedRecord = new Flour_Mills.PARTY();
_SelectedRecord.PARTY_ID = (string)((DataTable)SearchPartydataGrid.DataSource).Rows[e.RowIndex]["PARTY_ID"];
_SelectedRecord.NAME = (string)((DataTable)SearchPartydataGrid.DataSource).Rows[e.RowIndex]["NAME"];
Controller.PartyDAL.Load(_SelectedRecord.PARTY_ID);
this.Owner._selectedRecordFromSearchForm = _SelectedRecord; // set _searchRecoed to owners field
DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
You could declare _SelectedRecord as public in your search form and when the form closes you can access the variable like this :
if (frm.DialogResult == System.Windows.Forms.DialogResult.OK)
{
var SelectedRecord = frm._SelectedRecord;
}
I am following this exactly:
http://msdn.microsoft.com/en-us/library/ms185301.aspx
but can't get it to work. The form appears when I try and add my new item, but when I input text and click the button, nothing happens.
For posterity's sake here is my code:
The non-empty methods in the Wizard class which extends IWizard
public void RunStarted(object automationObject,
Dictionary<string, string> replacementsDictionary,
WizardRunKind runKind, object[] customParams)
{
try
{
// Display a form to the user. The form collects
// input for the custom message.
inputForm = new UserInputForm();
inputForm.ShowDialog();
customMessage = inputForm.get_CustomMessage();
// Add custom parameters.
replacementsDictionary.Add("$custommessage$",
customMessage);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
// This method is only called for item templates,
// not for project templates.
public bool ShouldAddProjectItem(string filePath)
{
return true;
}
The user input form code:
public partial class UserInputForm : Form
{
private string customMessage;
public UserInputForm()
{
InitializeComponent();
}
public string get_CustomMessage()
{
return customMessage;
}
private void button1_Click(object sender, EventArgs e)
{
customMessage = textBox1.Text;
this.Dispose();
}
}
And the button is indeed named button 1:
this.button1.Location = new System.Drawing.Point(200, 180);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(100, 40);
this.button1.TabIndex = 0;
this.button1.Text = "Click Me";
this.button1.UseVisualStyleBackColor = true;
So I don't have much experience with Windows Forms (do web apps), but I am following the directions on MSDN and it's pretty clear cut. Any suggestions? Can anyone else get this to work?
Okay I figured it out. I had to add the event handler in the form's constructor manually:
public UserInputForm()
{
InitializeComponent();
button1.Click += button1_Click;
}
Why this isn't in the documentation on MSDN boggles my mind.
If you use the WinForms designer mode to drag your button from the Toolbox, and then double-clicked the button in the designer view, it would have added the event handler and stubbed that Click method for you. Just FYI.