Dropdown ignors the adding of a default row to list
.CS
private const string DropDownListValue = "[All]";
private const string DropDownListText = "[All]";
private void LoadProduct()
{
try
{
FieldGoalEntities objEntity = new FieldGoalEntities();
IQueryable<Product> objProduct = from p in objEntity.Product
select p;
ddlProduct.Items.Clear();
if (objProduct != null)
{
ddlProduct.DataSource = objProduct;
ddlProduct.DataValueField = "ProductCode";
ddlProduct.DataTextField = "ProductCode";
ddlProduct.DataBind();
}
ddlProduct.Items.Insert(0, new ListItem(DropDownListText, DropDownListValue));
}
catch (Exception ex)
{
Common.LogEvent(Common.LoggingType.Error, "LoadProduct", ex.Message);
Common.ShowMessageBox(this.Master, "Error", "Load Product Status: " + ex.Message);
}
}
//ASPX
//DropdownBox
I need the all added for the filtering, but for some reason if I do the databinding in the .CS file it leaves out the [ALL]
I should call ddlProduct.DataBind(); after you've added All to the Items list
if (objProduct != null)
{
ddlProduct.DataSource = objProduct;
ddlProduct.DataValueField = "ProductCode";
ddlProduct.DataTextField = "ProductCode";
}
ddlProduct.Items.Insert(0, new ListItem(DropDownListText, DropDownListValue));
ddlProduct.DataBind();
Related
I have this DropDownList I bind it on the codebehind, when I put on IsPostBack always return null and when I put out always return the first value.
The code is this one:
if (!IsPostBack)
{
preencherAreas();
}
public void preencherAreas()
{
try
{
string[] areas = areaLocal.Area.Split(';');
List<Area> listAreas = new List<Area>();
foreach (var a in areas)
{
listAreas.Add(new Area(a, a.Replace(" ", "_")));
}
selectArea.DataSource = listAreas;
selectArea.DataTextField = "Text";
selectArea.DataValueField = "Value";
selectArea.DataBind();
}
catch (Exception)
{
}
}
I try to catch the value wit SelectedValue and with SelectedItem.Value and the result is always the same that I said
I'd like to re-use a dialog class for data manipulation. The data will be retrieved from database. It depends on which table the class retrieve the data from, the size of the table columns is not fixed, so I can't declare column variables. After users update data, I would like to convert the input data using setResultConverter but do not know how to refer to the variable, since the program generates TextFields dynamically. Please help. Here is the the code.
public class AddDialog {
private Dialog<DBtable> dialog = new Dialog<DBtable>();
private ButtonType saveBtn;
//database variables
private Connection connect; // = null;
private String dbTblName;
//gridpane content variables
private GridPane contentPane = new GridPane();
private HashMap<String, TextField> fieldMap =
new HashMap<String, TextField>();
private ArrayList<String> dataList = new ArrayList<String>();
public AddDialog (String title, String header, String dbTable) {
this.dbTblName = dbTable;
dialog.setTitle(title);
dialog.setHeaderText(header);
saveBtn = new ButtonType("Save", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(saveBtn,
ButtonType.CANCEL);
dialog.getDialogPane().setContent(getLayout(dbTable));
Optional<DBtable> result = dialog.showAndWait();
result.ifPresent(data -> {
System.out.println(" data="+data+" 0="+data.getID()+
" 1="+data.getField1());
});
} // constructor ends
public GridPane getLayout(String dbTable) {
String sql = "select column_name, description ";
sql += "from syscolumn_description ";
sql += "where table_name = \'" + dbTable + "\'";
String fieldLabel, fieldCol;
ResultSet ds = null;
// retrieve meta data from database
connect = DBConnect.getConnect(connect);
try {
Statement labelStmnt = connect.createStatement();
ds = labelStmnt.executeQuery(sql);
int row = 0;
while (ds.next()) {
row += 2;
//label....column=0 row=row+2;
fieldLabel = ds.getString("DESCRIPTION");
contentPane.add(new Text(fieldLabel), 0, row);
//textField...column=1 row=row+2;
contentPane.add(new TextField(), 1, row);
fieldCol = ds.getString("COLUMN_NAME");
fieldMap.put(fieldCol, new TextField());
} // while result set loop ends
} catch (Exception e) {
e.printStackTrace();
} finally {
try {if(ds != null) ds.close();} catch (Exception e) {};
}
// convert result
dialog.setResultConverter(dialogButton -> {
if (dialogButton == saveBtn) {
int i=0;
for (Map.Entry<String, TextField> e : fieldMap.entrySet()) {
dataList.add(e.getValue().getText());
i++;
System.out.println("col="+e.getKey()+
" data="+e.getValue().getText());
} // map loop end
return new DBtable(dataList, i);
}
return null;
});
return contentPane;
} //getLayout ends
} // AddDialog ends
I'm doing an app with Xamarin iOS.
I put a UITableView on XCode, so that when I click on a button, it retrieves from the database and slot it in. I'm able to put it onto a row, but couldn't figure it out how to have multiple rows of data in it. This is my partial code from which I'm able to display a row of data.
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
while (dr.Read())
{
var table = new UITableView(this.retrieveData.Frame);
string[] tableItems = new String[] {dr["admin_num"] + ", " + dr["name"]};
table.Source = new TableSource(tableItems);
Add (table);
}
You are creating a completely new TableView for each row in your data. Instead, you should loop through your data and create a data structure (List, array, etc) containing ALL of the data you want to display, and then pass that data to your TableView/Source.
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
// you will need a class mydata with Num and Name properties
List<mydata> data = new List<mydata>();
while (dr.Read())
{
data.Add(new mydata { Num = dr["admin_num"], Name = dr["name"] });
}
dr.Close();
var table = new UITableView(this.retrieveData.Frame);
table.Source = new TableSource(data);
Add (table);
What you need to do is this:
public List<DemoClass> getDemoClassList()
{
List<DemoClass> lstDemoClass;
DemoClass objDemoClass;
try
{
String strCommandText;
strCommandText = "SELECT * FROM DemoClass ";
command = new SqliteCommand(strCommandText, connection);
lstDemoClass = new List<DemoClass>();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
objDemoClass = new Homes(false);
objDemoClass.ID = Convert.ToInt32(reader[0]);
objDemoClass.Name = Convert.ToString(reader[1]);
lstDemoClass.Add(objDemoClass);
}
}
return lstDemoClass;
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Dispose();
command = null;
lstDemoClass = null;
objDemoClass = null;
}
}
public void BindList()
{
List<DemoClass> lstDemoClass = new List<DemoClass>();
DemoClass hm = new DemoClass();
lstDemoClass = (List<DemoClass>)hm.getDemoClassList();
TableViewDataSource tdatasource = new TableViewDataSource(this, lstDemoClass);
table.Hidden = false;
table.DataSource = tdatasource;
table.Delegate = new TableViewDelegate(this, table, lstDemoClass);
table.ReloadData();
}
The getDemoClassList() will give the retrieved list from SQLite table, and later you can bind the list to the table datasource.
UPDATE:
As per your request I have updated my comment with the code for datasource and its delegate classes.
Now in this same class you need to add the following subclasses:
#region TableDelegate
public class TableViewDelegate : UITableViewDelegate
{
private DemoPageViewController _Controller;
private List<DemoClass> lst;
public TableViewDelegate(DemoPageViewController controller ,UITableView tableView, List<DemoClass> tblList)
{
try
{
this._Controller = controller;
this.lst = tblList;
}
catch(Exception ex)
{
}
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
try
{
//This loads the activity spinner till the selection code is completed
_Controller._loadPop = new LoadingOverlay (new System.Drawing.RectangleF(0,0,_Controller.View.Frame.Width,_Controller.View.Frame.Height),"Loading...");
_Controller.View.Add ( _Controller._loadPop );
// spin up a new thread to do some long running work using StartNew
Task.Factory.StartNew (
// tasks allow you to use the lambda syntax to pass work
() => {
InvokeOnMainThread(delegate{
DemoClass f = lst[indexPath.Row];
//Add your code here, usually some navigation or showing a popup
});
}).ContinueWith(t => InvokeOnMainThread(() => {
//Hide the activity spinner
_Controller._loadPop.Hide();
}));
}
catch(Exception ex)
{
}
finally
{
}
}
}
#endregion
#region TableDataSource
private class TableViewDataSource : UITableViewDataSource
{
static NSString kCellIdentifier = new NSString("MyIdentifier");
private List<DemoClass> lst;
private DemoPageViewController controller;
public TableViewDataSource (DemoPageViewController controller ,List<DemoClass> tblLst)
{
this.controller = controller;
this.lst = tblLst;
}
public override int NumberOfSections (UITableView tableView)
{
return 1;
}
public override int RowsInSection (UITableView tableView, int section)
{
return lst.Count;
}
// Override to support conditional editing of the table view.
public override bool CanEditRow (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
// Return false if you do not want the specified item to be editable.
return false;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
try
{
UITableViewCell cell = tableView.DequeueReusableCell (kCellIdentifier);
if (cell == null)
{
cell = new UITableViewCell (UITableViewCellStyle.Subtitle, kCellIdentifier);
cell.Tag = Environment.TickCount;
}
DemoClass objDemo = lst[indexPath.Row];
cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
cell.ImageView.Image = UIImage.FromFile("Images/CameraImg.png");
cell.DetailTextLabel.Text = "Show some detail: " + objDemo.DemoDescription.ToString();
cell.TextLabel.Text = "Some Title: " + objDemo.DemoTitle.ToString();
return cell;
}
catch(Exception ex)
{
return null;
}
finally
{
}
}
}
#endregion
Hope it helps.
I am having a database and I use it through Entity Framework, I need to update the data by editing the other items in text boxes and grid, that is working fine and below is the code:
In aspx.cs
protected void SaveBtn_Click(object sender, EventArgs e)
{
obj.Address = AppAddress.Text;
obj.City = AppCity.Text;
obj.Email = AppEmail.Text;
obj.Notes = AppComments.Text;
obj.Postal = AppPostal.Text;
obj.AppraiserAppraiserCompanyId = ApprCompCmbx.SelectedIndex;
obj.ProvinceState = Province.SelectedIndex;
apprblobj.GetUpdate(obj);
Response.Write("<script>alert('You have successfully updated the Data');</script>");
}
call in the BL:
public void GetUpdate(Appraiser appObj)
{
obj.UpdateData(appObj);
}
and in the DAL
public void UpdateData(Appraiser apprObj)
{
try
{
var Appsave = context.Appraisers.FirstOrDefault(App => App.AppraiserId == apprObj.AppraiserId);
if (Appsave != null)
{
Appsave.AppraiserName = apprObj.AppraiserName;
Appsave.AppraiserAppraiserCompanyId = apprObj.AppraiserAppraiserCompanyId;
Appsave.Address = apprObj.Address;
Appsave.City = apprObj.City;
Appsave.ProvinceState = apprObj.ProvinceState;
Appsave.Email = apprObj.Email;
Appsave.Postal = apprObj.Postal;
Appsave.Notes = apprObj.Notes;
context.SaveChanges();
}
}
catch (Exception ex)
{
log.Debug("Appraiser : UpdateData: " + ex.Message + " Trace : " + ex.StackTrace);
}
}
Now I wanto to add a new item through the same combobox and on the button click functionality as it is doing all the work like add, update and delete.
Kindly provide me the hint: This I know that addobject(__) will ve used in place of savechanges etc.
I keep getting the following error and I don't know how to fix it. Any help would be great please
Exception Details:NullReferenceException was unhandled by users code: Object reference not set to an instance of an object.
protected void LbUpload_Click(object sender, EventArgs e)
{
ERROR: if(FileUpload.PostedFile.FileName == string.Empty)
{
LabelMsg.Visible = true;
return;
}
else
{
string[] FileExt = FileUpload.FileName.Split('.');
string FileEx = FileExt[FileExt.Length - 1];
if (FileEx.ToLower() == "csv")
{
FileUpload.SaveAs(Server.MapPath("CSVLoad//" + FileUpload.FileName));
}
else
{
LabelMsg.Visible = true;
return;
}
}
CSVReader reader = new CSVReader(FileUpload.PostedFile.InputStream);
string[] headers = reader.GetCSVLine();
DataTable dt = new DataTable();
foreach (string strHeader in headers)
dt.Columns.Add(strHeader);
string[] data;
while ((data = reader.GetCSVLine()) != null)
dt.Rows.Add(data);
GridView1.DataSource = dt;
GridView1.DataBind();
if (FileUpload.HasFile)
try
{
FileUpload.SaveAs(Server.MapPath("confirm//") +
FileUpload.FileName);
LabelGrid.Text = "File name: " +
FileUpload.PostedFile.FileName + "<br>" +
FileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload.PostedFile.ContentType + "<br><b>Uploaded Successfully";
}
catch (Exception ex)
{
LabelGrid.Text = "ERROR: " + ex.Message.ToString();
}
else
{
LabelGrid.Text = "You have not specified a file.";
}
File.Delete(Server.MapPath("confirm//" + FileUpload.FileName));
}
You are checking if the FileName is string.Empty, it sounds like you want to detect when the user clicked the button without selecting a file.
If that happens, the actual PostedFile property will be null (remember, the user didn't posted a file), you should use the FileUpload.HasFile property for that purpose:
protected void LbUpload_Click(object sender, EventArgs e)
{
if(FileUpload.HasFile)
{
LabelMsg.Visible = true;
return;
}
// ...
}
But I would recommend you also to add a RequiredFieldValidator.
More on validation:
Validating ASP.NET Server Controls
ASP.NET Validation in Depth
Are you sure that FileUpload and FileUpload.PostedFile is not null?
Either FileUpload or its PostedFile property must be null.