I'm new in using JComboBox, I wanted to populate JComboBox from my MSAccess Database. I have the following codes:
public check_Writer() //Constructor
{
gui();
fillCombo();
}
public void gui()
{
JFrame mainFrame = new JFrame("Frame");
mainFrame.setSize(500,500);
mainFrame.setVisible(true);
JPanel mainPanel = new JPanel();
mainPanel.setBackground(color.BLUE);
mainFrame.add(mainPanel);
JComboBox listofSuppliersCombo = new JComboBox()
mainPanel.add(listofSuppliersCombo);
}
public void fillCombo()
{
String dataSourceName = "CheckWriterDB";
String db = "jdbc:odbc:" + dataSourceName;
try
{
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Connection conn = DriverManager.getConnection(db, "", "");
Statement st1 = conn.createStatement();
st1.execute("select Suppliers from SuppliersTable");
ResultSet rs1 = st1.getResultSet();
if (rs1!null)
{
while(rs1.next())
{
System.out.println(rs1.getString(1));
}
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e)
}
}
}
I edited my codes sir, my code works just fine i can print my data in the console, but i can't populate my JComboBox, I tried this code, listOfSuppliersCombo.addItem(rs1.getString(1)); but error message(java.lang.NullPointerException). Is there something wrong with the way created my combo box above, thank you very much sir.
You have defined listofSuppliersCombo locally in gui function, in order to reference any object, in two different mehods, you need to declare it in upper scope.
Your code will work if you try like below:
JComboBox listofSuppliersCombo;
public void gui()
{
//Your Code
listofSuppliersCombo=new JComboBox();
//Your Code
}
public void fillCombo()
{
//Your Code
listofSuppliersCombo.addItem("Your Item");
//Your Code
}
Related
My code in controller
public List<Addresses> Addresses_FindByPartialStreetAddress(string partialnumber, string partialstreet)
{
using (var context = new A09Context())
{
var results = context.Database.SqlQuery<Addresses>(
"Addresses_FindByPartialStreetAddress #number, #street",
new SqlParameter("number", partialnumber), new SqlParameter("street", partialstreet));
return results.ToList();
}
my code in webform page, I'm not sure how to implement partial search from two text fields to pull a selection of list.. I know I'm doing something wrong here
protected void SearchAddress_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(SearchPartialNumber.Text))
{
errormsgs.Add("Enter a partial address number to search.");
LoadMessageDisplay(errormsgs, "alert alert-info");
}
if (string.IsNullOrEmpty(SearchPartialStreet.Text))
{
errormsgs.Add("Enter a partial address street to search.");
LoadMessageDisplay(errormsgs, "alert alert-info");
}
else
{
try
{
AddressesController sysmgr = new AddressesController();
List<Addresses> info =
sysmgr.Addresses_FindByPartialStreetAddress
(SearchPartialNumber.Text + SearchPartialStreet);
AddressSelectionList.DataSource = info;
AddressSelectionList.DataBind();
}
I binded my list like this
protected void BindAddressSelectionList()
{
try
{
AddressesController sysmgr = new AddressesController();
List<Addresses> info = sysmgr.Addresses_List();
// info.Sort((x, y) => x.Number.CompareTo(y.Number));
AddressSelectionList.DataSource = info;
AddressSelectionList.DataTextField = "street";
AddressSelectionList.DataValueField = "number";
AddressSelectionList.DataBind();
AddressSelectionList.Items.Insert(0, "select ...");
}`
Click here to see what the form looks like
OK...
I was finally making some headway with creating a User Management page using Identity 2 in Web Forms.
It was mostly moving along just fine. When suddenly I run into this issue, and it makes no sense to me.
I have an AS form with a dropdown list of Roles. That list is populated using
roleMgr.Roles.ToList();
Works Great
I use the user being edited Role to set the current selected value.
ddlUserType.SelectedValue = user.Roles.FirstOrDefault().ToString();
This WAS working like dynamite
Last week...
Now all of a sudden user.Roles.FirstOrDefault().ToString(); is returning
"System.Data.Entity.DynamicProxies.IdentityUserRole_FDDE5D267CF62D86904A3BC925D70DC410F12D5BE8313308EC89AC8537DC6375"
What he heck, man?
So I tried user.Roles.Take(1).ToString();
That returns
"System.Linq.Enumerable+d__24`1[Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole]"
I have to presume I Broke, Something...
But What?
Nothing in this code page changed at all between when it worked and then didn't.
The only thing I did related to Identity at all was Migrate a couple of fields into AspNetUsers (another whole ballgame, migrations...) which also worked like dynamite BTW.
I even went to the extreme of wiping out my Migrations and AspNet user tables entirely, and re-initializing it all.
Any suggestions ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Sperry_Parts.Models;
using Sperry_Parts.Logic;
using Microsoft.AspNet.Identity.Owin;
using Owin;
namespace Parts.Admin
{
public partial class CreateEditUser : System.Web.UI.Page
{
private bool NewUser
{
get { return ViewState["NewUser"] != null ? (bool)ViewState["NewUser"] : false; }
set { ViewState["NewUser"] = value; }
}
private string EditUser
{
get { return (string)ViewState["EditUser"]; }
set { ViewState["EditUser"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
EditUser = Session["Edit_User"].ToString();
// Access the application context and create result variables.
Models.ApplicationDbContext context = new ApplicationDbContext();
RoleActions roleAction = new RoleActions();
// Create a RoleStore object by using the ApplicationDbContext object.
var roleStore = new RoleStore<IdentityRole>(context);
// Create a RoleManager object that is only allowed to contain IdentityRole objects.
var roleMgr = new RoleManager<IdentityRole>(roleStore);
// Load the DDL of Roles
var roles = roleMgr.Roles.ToList();
ddlUserType.DataTextField = "Name";
ddlUserType.DataValueField = "Id";
ddlUserType.DataSource = roles;
ddlUserType.DataBind();
if (EditUser == "")
{
txtUserName.Enabled = true;
txtUserName.Focus();
NewUser = true;
} // End New User
else
{
// User part
var userMgr = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
txtUserName.Enabled = false;
txtFullName.Focus();
var user = userMgr.FindByName(EditUser);
if (user != null)
{
txtUserName.Text = user.UserName;
txtUserEmail.Text = user.Email;
txtFullName.Text = user.FullName;
var hisroles = user.Roles.ToList(); // properly returns 1 item
// this is where it went off the rails - these 4 lines are debugging code
string xrole = user.Roles.FirstOrDefault().ToString();
string role2 = user.Roles.Take(1).ToString();
string trythis = xrole.ToString();
string trythis2 = role2.ToString();
// I swear, this worked last week...
ddlUserType.SelectedValue = user.Roles.FirstOrDefault().ToString();
}
} // End Editing User
} // End if (!IsPostBack)
} // End Page Load
protected void CreateUser()
{
// removed as non-relevant to question
} // End CreateUser
protected void UpdateUser()
{
// removed as non-relevant to question
} // End UpdateUser
protected void btnSave_Click(object sender, EventArgs e)
{
// removed as non-relevant to question
} // End btnSave
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("~/ManageUsers");
} // End btnCancel
} // End Class CreateEditUser
}
I ran into the same problem trying to set the value of a "Roles" DropDownList inside a GridView Control. I solved it by using:
user.Roles.First().RoleId
It just happens that my RoleId is also my role name.
I am trying to connect an SQLite database file to a picker component (accepting strings). This should act similar to a drop-down menu. I have tried to follow previous advice and examples, but without success.
As indicated in a previous post, I have saved the database file in the source folder of the application. View of the source folder where I have saved the database file (highlighted).
The code I have used to implement my app is as follows with the below layout.
//-----------------------
database code
//-----------------------
public class MyApplication {
private Form current;
private Resources theme;
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Pro only feature, uncomment if you have a pro subscription
// Log.bindCrashProtection(true);
}
private Container Home() {
Container home = new Container(new BoxLayout(BoxLayout.Y_AXIS));
return home;
}
private Container AddItem() {
Container addItem = new Container(new BoxLayout(BoxLayout.Y_AXIS));
TextArea item = new TextArea("Add Item");
addItem.addComponent(item);
Picker selectItem = new Picker();
selectItem.setType(Display.PICKER_TYPE_STRINGS);
//----------------------------------------------------------------------------------
Database db = null;
Cursor cur = null;
try {
db = Display.getInstance().openOrCreate("FoodAndBeverage.db");
if(selectItem.getText().startsWith("Still Water")) {
cur = db.executeQuery(selectItem.getText());
int columns = cur.getColumnCount();
addItem.removeAll();
if(columns > 0) {
boolean next = cur.next();
if(next) {
ArrayList<String[]> data = new ArrayList<>();
String[] columnNames = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
columnNames[iter] = cur.getColumnName(iter);
}
while(next) {
Row currentRow = cur.getRow();
String[] currentRowArray = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
currentRowArray[iter] = currentRow.getString(iter);
}
data.add(currentRowArray);
next = cur.next();
}
Object[][] arr = new Object[data.size()][];
data.toArray(arr);
addItem.add(BorderLayout.CENTER, new Table(new DefaultTableModel(columnNames, arr)));
} else {
addItem.add(BorderLayout.CENTER, "Query returned no results");
}
} else {
addItem.add(BorderLayout.CENTER, "Query returned no results");
}
} else {
db.execute(selectItem.getText());
addItem.add(BorderLayout.CENTER, "Query completed successfully");
}
addItem.revalidate();
} catch(IOException err) {
Log.e(err);
addItem.removeAll();
addItem.add(BorderLayout.CENTER, "Error: " + err);
addItem.revalidate();
} finally {
Util.cleanup(db);
Util.cleanup(cur);
}
//---------------------------------------------------------------------------------------------
addItem.addComponent(selectItem);
TextField quantity = new TextField("", "Quantity (ml or g)", 4, TextArea.NUMERIC);
addItem.addComponent(quantity);
Button add = new Button("Add");
addItem.addComponent(add);
TextArea results = new TextArea("Results");
addItem.addComponent(results);
return addItem;
}
private Container Settings() {
Container settings = new Container(new BoxLayout(BoxLayout.Y_AXIS));
TextArea nutrients = new TextArea("Target");
settings.addComponent(nutrients);
TextField volume = new TextField("", "Volume (ml)", 4, TextArea.NUMERIC);
settings.addComponent(volume);
TextArea duration = new TextArea("Hydration Duration");
settings.addComponent(duration);
settings.add("Start:");
Picker start = new Picker();
start.setType(Display.PICKER_TYPE_TIME);
settings.addComponent(start);
settings.add("End:");
Picker end = new Picker();
end.setType(Display.PICKER_TYPE_TIME);
settings.addComponent(end);
Button save = new Button("Save");
settings.addComponent(save);
return settings;
}
public void start() {
if(current != null)
{
current.show();
return;
}
Form home = new Form("Hydrate", new BorderLayout());
Tabs t = new Tabs();
t.addTab("Home", Home());
t.addTab("Intake", AddItem());
t.addTab("Settings", Settings());
home.add(BorderLayout.NORTH, t);
home.show();
}
public void stop() {
current = Display.getInstance().getCurrent();
}
public void destroy() {
}
}
I would therefore appreciate any advice and guidance on exactly where I am going wrong and how to implement the suggested changes in my code.
I'm assuming the file under src does indeed end with the extension db as the Windows hidden extensions nonsense is turned on.
This code will NOT open a db placed in src:
db = Display.getInstance().openOrCreate("FoodAndBeverage.db");
You need to do something like this to implicitly initialize the DB the first time the app is installed:
String path = Display.getInstance().getDatabasePath("FoodAndBeverage.db");
FileSystemStorage fs = FileSystemStorage.getInstance();
if(!fs.exists(path)) {
try (InputStream is = Display.getInstance().getResourceAsStream(getClass(), "/FoodAndBeverage.db");
OutputStream os = fs.openOutputStream(path)) {
Util.copy(is, os);
} catch(IOException err) {
Log.e(err);
}
}
db = Display.getInstance().openOrCreate("FoodAndBeverage.db");
Notice that the code above doesn't check for updates of the DB so assuming the DB is read only you might want to update/merge it with app updates.
The above code doesn't work on Android device, this works only on simulator. I have tested multiple times in the android device. In the real android device ,the database is not loaded at all, shows sql exception error
"No such table sql exception".
Looks like preloaded sqlite .db file is never tested on real Android device.
public partial class ChatUserControl : System.Web.UI.UserControl
{
UserChatClass ucc = new UserChatClass();
public ChatUserControl()
{
lblChatFriend = new Label();
txtChatMessage = new TextBox();
imgFriend = new Image();
rpChatMessages = new Repeater();
}
public string ChatFriend { get { return this.lblChatFriend.Text; } set { this.lblChatFriend.Text = value; } }
public string imgFriendUrl { get { return this.imgFriend.ImageUrl; } set { this.imgFriend.ImageUrl = value; } }
public object rpChatDataSource { get { return this.rpChatMessages.DataSource; } set { this.rpChatMessages.DataSource = value; } }
public Repeater rpChatMessagesToBind { get { return this.rpChatMessages; } set { this.rpChatMessages = value; } }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ChatUserControl user1 = new ChatUserControl();
divChatUserControlCover.Controls.Add(user1);
}
}
private void BindUserControls()
{ ChatUserControl user1 = divChatUserControlCover.Controls[1] as ChatUserControl;
user1.ChatFriend = row["username"].ToString();
user1.imgFriendUrl = "../../HttpImageHandler.jpg?username=" + row["username"].ToString();
DataSet dsCM = ucc.GetChatMessages(Session["username"].ToString(), row["username"].ToString());
user1.rpChatDataSource = dsCM;
user1.DataBindForRpChatMessagesToBind();
user1.Visible = true;
}
Master.aspx
<div id="divChatUserControlCover" runat="server">
</div>
Ok I have edited the code and now I have created properties. How do I call the DataBind method for rpChatMessages? I also cant see my usercontrol on page. Why
I'm not sure if your trying to reference the first label or second label. If its the second lable you can't just do chatMessage. you would have to do
((Label)rpChatMessages.FindControl("chatMessage")) due to scope of controls.
When you reference a component inside another component (ie Repeater) the child component no longer belongs to the document (implied this) but rather belongs to the control, ie
this.rpChatMessages { chatMessage }
I think you are just trying to pass a value to one control inside a UserControl if this is correct, declare a public property like this:
ASCX code behind
public string MyProperty
{
get
{
return this.lbl.Text;
}
set
{
this.lbl.Text = value;
}
}
Setting the value to the UserControl
private void BindUserControls()
{
ChatUserControl user1 = divChatUserControlCover.Controls[1] as ChatUserControl;
user1.MyProperty = row["username"].ToString();
Setting the value in the page markup
<uc1:ChatUserControl MyProperty='<%# Eval("some field") %>' ...
Edit 1
Remove that line
public object rpChatDataSource { get { return this.rpChatMessages.DataSource; } set { this.rpChatMessages.DataSource = value; }
And instead add a method
public void BindMyRepeaterOrWhatever(IEnumerable<Yourentity> data)
{
this.myDataBoundControl.DataSource = data;
this.myDataBoundControl.DataBind();
}
You can change the IEnumerable<Yourentity> data for object data but if you can pass a strongly typed enumeration would be better
To my surprise I found why my user control's child controls dont get instantiated. Its because ChatUserControl user1 = new ChatUserControl() doesnt get its child controls initialized.
The proper way to create a new intance of user control is this way....
ChatUserControl user1 = (ChatUserControl)Page.LoadControl("~/ChatUserControl.ascx");
I am woefully new to generics, being tied to the support of a corporate intranet web application whose upgrade process is bound to red tape and slowwwly-changing standards. Consequently, today (thankfully!) I finally find myself scrambling during our upgrade to .Net 3.5 and transitioning all the code I can to a properly tiered model.
I have been reading all morning about generics trying to digest how to transition dropdown user controls into a proper business object that gets its data from a class in the data access layer.
There is a perfectly succinct question here that details exactly what I am interested in exploring: Set selected index in a Dropdownlist in usercontrol.
What I would love to see, however, is what Travel_CarSizes.GetCarSizes() actually looks like inside and how the class Travel_CarSizes is defined. (I am having a hard time with <T> and knowing where it should occur.)
For my own specific circumstance at the moment I need a dropdown user control to contain location directionals (N, S, W, C/O, NW, SE, etc) that are stored in a SQL table in the DB and whose selected index needs to be able to be set by whichever page it happens to be in, when form data exists.
I have begun to implement the model in the example from the link above but right now without using Generics because I can't figure it out:
The dropdown user control:
public partial class DropDownStreetPrefix : System.Web.UI.UserControl
{
public string StreetPrefixValue
{
get { return ddlStreetPrefix.SelectedValue.ToString(); }
set
{
Bind();
ddlStreetPrefix.SelectedIndex = ddlStreetPrefix.Items.IndexOf(ddlStreetPrefix.Items.FindByValue(value));
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Bind();
}
}
private void Bind()
{
if (ddlStreetPrefix.Items.Count == 0)
{
SqlDataReader rdr = StreetDirectionals.GetDirectionals();
ddlStreetPrefix.DataSource = rdr;
ddlStreetPrefix.DataBind();
ddlStreetPrefix.DataValueField = "StreetSuffixPrefixAbbr";
ddlStreetPrefix.DataTextField = "StreetSuffixPrefixAbbr";
ListItem li = new ListItem("", "");
ddlStreetPrefix.Items.Insert(0, li);
ddlStreetPrefix.SelectedIndex = 0;
}
}
}
The StreetDirectionals class:
public class StreetDirectionals
{
private StreetDirectionals () { }
public static SqlDataReader GetDirectionals ()
{
string sqlText = "SELECT StreetSuffixPrefixAbbr FROM common..tblStreetSuffixPrefix " +
"ORDER BY StreetSuffixPrefixAbbr";
SqlDataReader rdr = SqlClient.ExecuteFetchReturnDataReader( theConnectionString, CommandType.Text, sqlText);
return rdr;
}
}
I will separate out the database interaction inside the StreetDirectionals class as soon as I can figure out how to change its code if I were to transform the Bind() method from my dropdown user control into this:
private void Bind()
{
if (!IsPostBack)
{
**List<StreetDirectionals> sd = StreetDirectionals.GetDirectionals();**
ddlStreetPrefix.DataSource = sd;
ddlStreetPrefix.DataTextField = "StreetSuffixPrefixAbbr";
ddlStreetPrefix.DataValueField = "StreetSuffixPrefixAbbr";
ddlStreetPrefix.DataBind();
}
}
Any assistance would be sooo much appreciated!
public class StreetDirectional
{
public string StreetSuffixPrefixAbbr { get; set; }
public static IEnumerable<StreetDirectional> GetDirectionals ()
{
string sqlText = "SELECT StreetSuffixPrefixAbbr FROM common..tblStreetSuffixPrefix "
+ "ORDER BY StreetSuffixPrefixAbbr";
SqlDataReader rdr = SqlClient.ExecuteFetchReturnDataReader( theConnectionString, CommandType.Text, sqlText);
var list = new List<StreetDirectional>();
while (rdr.Read())
{
var item = new StreetDirectional() { StreetSuffixPrefixAbbr = (string)rdr["StreetSuffixPrefixAbbr"] };
list.Add(item);
}
return list;
}
}
then you can do this
ddlStreetPrefix.DataSource = StreetDirectional.GetDirectionals();