Remove an item from listbox in WP8 - windows-phone-8

I'm new to windows phone development. I'm trying to delete selected item from the list box. I've got dataclass
public class MyDataClass
{
public string MSG { get; set; }
public int Id { get; set; }
}
Then I try to delete the selected item (Button1_Click event)
MyDataClass item = MyDict.SelectedItem as MyDataClass;
ObservableCollection dataList = new ObservableCollection();
dataList.Remove(item);
The problem in creating the datalist in task, so it's no availble for the rest of the program, how to change this?
public async Task GETFROMDB()
{
int a = 1;
Database database = new Database(ApplicationData.Current.LocalFolder, "DictData.db");
await database.OpenAsync();
string query = "SELECT * FROM MyDICT";
Statement statement = await database.PrepareStatementAsync(query);
statement.EnableColumnsProperty();
ObservableCollection<MyDataClass> dataList = new ObservableCollection<MyDataClass>();
while (await statement.StepAsync())
{
rawData = string.Format(statement.Columns["value"]);
string[] sep = new string[] { "\r\n" }; //Splittng it with new line
string[] arrData = rawData.Split(sep, StringSplitOptions.RemoveEmptyEntries);
foreach (var d in arrData)
{
dataList.Add(new MyDataClass() { MSG = d, Id= a });
a++;
}
}
MyDict.ItemsSource = dataList;
}

Can you make binding to a dataList outside the Task and make dataList static or reference to it in a Task?
When creating a list:
static ObservableCollection<MyDataClass> dataList = new ObservableCollection<MyDataClass>();
MyDict.ItemsSource = dataList;
Then in Task:
public async Task GETFROMDB()
{
int a = 1;
Database database = new Database(ApplicationData.Current.LocalFolder, "DictData.db");
await database.OpenAsync();
string query = "SELECT * FROM MyDICT";
Statement statement = await database.PrepareStatementAsync(query);
statement.EnableColumnsProperty();
while (await statement.StepAsync())
{
rawData = string.Format(statement.Columns["value"]);
string[] sep = new string[] { "\r\n" }; //Splittng it with new line
string[] arrData = rawData.Split(sep, StringSplitOptions.RemoveEmptyEntries);
foreach (var d in arrData)
{
dataList.Add(new MyDataClass() { MSG = d, Id= a });
a++;
}
}
}
Then in Click:
MyDataClass item = MyDict.SelectedItem as MyDataClass;
dataList.Remove(item);
Or make it:
When creating a list:
ObservableCollection<MyDataClass> dataList = new ObservableCollection<MyDataClass>();
MyDict.ItemsSource = dataList;
Then in Task:
public async Task GETFROMDB(ObservableCollection<MyDataClass> dataList)
{
int a = 1;
Database database = new Database(ApplicationData.Current.LocalFolder, "DictData.db");
await database.OpenAsync();
string query = "SELECT * FROM MyDICT";
Statement statement = await database.PrepareStatementAsync(query);
statement.EnableColumnsProperty();
while (await statement.StepAsync())
{
rawData = string.Format(statement.Columns["value"]);
string[] sep = new string[] { "\r\n" }; //Splittng it with new line
string[] arrData = rawData.Split(sep, StringSplitOptions.RemoveEmptyEntries);
foreach (var d in arrData)
{
dataList.Add(new MyDataClass() { MSG = d, Id= a });
a++;
}
}
}
Then in Click:
MyDataClass item = MyDict.SelectedItem as MyDataClass;
dataList.Remove(item);
Of course you need to wait until the Task is finished.

you appear to be trying to remove the item from a brand new collection - try instead to remove it from the one that your listbox is data bound to.

Try using the button data context
like this
in your click handler
private void ButtonClick(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
if (btn != null)
{
MyDataClass item = btn.DataContext as MyDataClass;
dataList.Remove(item);
}
}

Related

CsvHelper wrap all values with quotes

I am using CsvHelper I need to wrap all values with quotes.
Is that possible?
Data = is a List
using (StreamWriter textWriter = new StreamWriter(path))
{
textWriter.BaseStream.Write(p, 0, p.Length);
// var dt = new DataTable();
var csv = new CsvWriter(textWriter);
csv.WriteRecords(Data);
textWriter.Flush();
textWriter.Close();
}
Thanks
There is a config value called ShouldQuote where you can determine on a field level if it should be quoted.
void Main()
{
var records = new List<Foo>
{
new Foo { Id = 1, Name = "one" },
new Foo { Id = 2, Name = "two" },
};
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer))
{
csv.Configuration.ShouldQuote = (field, context) => true;
csv.WriteRecords(records);
writer.ToString().Dump();
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
Output:
"Id","Name"
"1","one"
"2","two"
From version 25.0.0 up to the date, the way of doing it is:
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
ShouldQuote = args => true
};
Just need to add a configuration object. like this
CsvHelper.Configuration.CsvConfiguration config = new CsvHelper.Configuration.CsvConfiguration();
config.QuoteAllFields = true;
var csv = new CsvWriter(textWriter, config);

UWP - writing to JSON without owerwrite data

I want to write data to JSON file, without overwriting them. I am using this code
Item test = new Item("test", 23);
try
{
var Folder = Windows.Storage.ApplicationData.Current.LocalFolder;
//var file = await Folder.CreateFileAsync("data.json", Windows.Storage.CreationCollisionOption.ReplaceExisting);
var file = await Folder.GetFileAsync("data.json");
var data = await file.OpenStreamForWriteAsync();
using (StreamWriter r = new StreamWriter(data))
{
var serelizedfile = JsonConvert.SerializeObject(test);
r.Write(serelizedfile);
}
}
catch (Exception a)
{
throw a;
}
Noticed that you're possibly using the Json.NET for serialization and deserialization the Json file. I think it's better to deserialize the list of Json object and you can operate on this list, then serialize the new list to Json and save into the file, not directly serialize one item and write it into the file.
For example, my Json file is like this:
[
{"color":"red","value":"#f00"},
{"color":"green","value":"#0f0"},
{"color":"blue","value":"#00f"},
{"color":"cyan","value":"#0ff"},
{"color":"magenta","value":"#f0f"},
{"color":"yellow","value":"#ff0"},
{"color":"black","value":"#000"}
]
code for adding one item to this file:
if (file != null)
{
using (var streamIn = await file.OpenAsync(FileAccessMode.ReadWrite))
{
DataReader reader = new DataReader(streamIn);
await reader.LoadAsync((uint)streamIn.Size);
var jsonInstring = reader.ReadString((uint)streamIn.Size);
var JobjList = JsonConvert.DeserializeObject<List<JsonColor>>(jsonInstring);
reader.Dispose();
JobjList.Add(new JsonColor() { color = "pink", value = "#c0c" });
JsonOutstring = JsonConvert.SerializeObject(JobjList);
}
using (var streamOut = await file.OpenAsync(FileAccessMode.ReadWrite))
{
DataWriter writer = new DataWriter(streamOut);
writer.WriteString(JsonOutstring);
await writer.StoreAsync();
writer.DetachStream();
writer.Dispose();
}
}
else
{
}
My class object:
public class JsonColor
{
public string color { get; set; }
public string value { get; set; }
}
As you can see, I deserialized the Json file and get the List<JsonColor>, then I added one item new JsonColor() { color = "pink", value = "#c0c" } to this list, and finally serialized this new list and save it. So for your scenario, you can modify the Json file and my JsonColor class to fit your need.
Update:
private string JsonOutstring;
private async void Button_Click(object sender, RoutedEventArgs e)
{
//create a json file, if the file is exit, then open it.
var local = Windows.Storage.ApplicationData.Current.LocalFolder;
var Jsonfile = await local.CreateFileAsync("test.json", Windows.Storage.CreationCollisionOption.OpenIfExists);
if (Jsonfile != null)
{
ReadAndWriteJsonFile(Jsonfile);
}
else
{
}
}
public async void ReadAndWriteJsonFile(StorageFile file)
{
using (var streamIn = await file.OpenAsync(FileAccessMode.ReadWrite))
{
DataReader reader = new DataReader(streamIn);
await reader.LoadAsync((uint)streamIn.Size);
var jsonInstring = reader.ReadString((uint)streamIn.Size);
var JobjList = JsonConvert.DeserializeObject<List<JsonColor>>(jsonInstring);
reader.Dispose();
if (JobjList == null)
{
JobjList = new List<JsonColor>();
}
JobjList.Add(new JsonColor() { color = "pink", value = "#c0c" });
JsonOutstring = JsonConvert.SerializeObject(JobjList);
}
using (var streamOut = await file.OpenAsync(FileAccessMode.ReadWrite))
{
DataWriter writer = new DataWriter(streamOut);
writer.WriteString(JsonOutstring);
await writer.StoreAsync();
writer.DetachStream();
writer.Dispose();
}
}
public class JsonColor
{
public string color { get; set; }
public string value { get; set; }
}

Removing First Item from listbox while binding to listbox

I have parsed the feed http://www.toucheradio.com/toneradio/android/toriLite/AndroidRSS.xml
And all items from rss feed displayed in listbox.Now I dont want to get first item I have to omit it.How Can I do it.
MainPage.xaml.cs:
namespace tori
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// is there network connection available
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
MessageBox.Show("No network connection available!");
return;
}
// start loading XML-data
WebClient downloader = new WebClient();
Uri uri = new Uri(" http://www.toucheradio.com/toneradio/android/toriLite/AndroidRSS.xml", UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ChannelDownloaded);
downloader.DownloadStringAsync(uri);
}
void ChannelDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the XML-file!");
}
else
{
// Deserialize if download succeeds
XDocument document = XDocument.Parse(e.Result);
var queue = from item in document.Descendants("item")
select new Item
{
title = item.Element("title").Value
,
link = item.Element("link").Value
,
ThumbnailUrl = item.Element(item.GetNamespaceOfPrefix("media") + "thumbnail").Attribute("url").Value
,
};
itemsList.ItemsSource = queue;
}
}
public class Item
{
public string title { get; set; }
public string ThumbnailUrl { get; set; }
public string link { get; set; }
}
If I write queue.RemoveAt(0);
i was getting error at RemoveAt.
Can anybody please tell me how can I do that.
Many Thanks in advance.
You can easily do this using LINQ Skip extension method (documentation here).
Just try the sample below:
itemsList.ItemsSource = queue.Skip(1);
As well you can rewrite the query to omit the first item before applying the projection in the select method using the methods chain approach:
var queue = document.Descendants("item")
.Skip(1)
.Select(item => new Item
{
title = item.Element("title").Value,
link = item.Element("link").Value,
ThumbnailUrl = item.Element(item.GetNamespaceOfPrefix("media") + "thumbnail").Attribute("url").Value,
})
.ToList();
itemsList.ItemsSource = queue;
UPDATE / DUE TO COMMENTS
And as well if you need to skip items at certain indexes you may use the Where method and the HasSet as in the sample below:
var document = XDocument.Parse(e.Result);
var indexes = new HashSet<int> { 1, 3, 4 };
var queue = document.Descendants("item")
.Select(item => new Item
{
title = item.Element("title").Value,
link = item.Element("link").Value,
ThumbnailUrl =
item.Element(item.GetNamespaceOfPrefix("media") + "thumbnail").Attribute("url").Value,
})
.Where((x, i) => !indexes.Contains(i))
.ToList();
Items.ItemsSource = queue;

JTable unable to change cell value

I have created a method to created JTable as per below:
public void refTable(String jobNo) {
Report rp = new Report();
final String noJob = jobNo;
Map<Integer, String> jMap = rp.getReportInfo(jobNo);
Map<Integer, String> sortedMap = new TreeMap<Integer, String>(jMap);
String[] row = new String[sortedMap.size()];
Integer[] no = new Integer[sortedMap.size()];
String[] stat = new String[sortedMap.size()];
Boolean[] dev = new Boolean[sortedMap.size()];
String[] remark = new String[sortedMap.size()];
Boolean[] rem = new Boolean[sortedMap.size()];
userRemark = new String[sortedMap.size()];
tabSize = sortedMap.size();
int i = 0;
for (Integer key : sortedMap.keySet()) {
no[i] = key;
String[] val = sortedMap.get(key).split("###");
if (val[0].trim().equals("DEV")) {
stat[i] = "FAIL";
} else {
stat[i] = val[0].trim();
}
row[i] = val[1].trim();
dev[i] = false;
remark[i] = "";
//remark[i] = false;
//if(userRemark1[i]!=null)
userRemark[i] = RemarkDropDownList.userOthersReamrk;
//else
//userRemark[i] ="";
rem[i] = false;
i++;
}
DefaultTableModel model = new DefaultTableModel();
model.fireTableDataChanged();
jTable1.setModel(model);
model.addColumn("No:", no);
model.addColumn("Status:", stat);
model.addColumn("Details:", row);
model.addColumn("Non-Deviation", dev);
model.addColumn("Remarks", remark);
model.addColumn("Remove", rem);
model.addColumn("UR", userRemark);
TableColumn col1 = jTable1.getColumnModel().getColumn(0);
col1.setPreferredWidth(30);
TableColumn col2 = jTable1.getColumnModel().getColumn(1);
col2.setPreferredWidth(30);
TableColumn col3 = jTable1.getColumnModel().getColumn(2);
TextRenderer renderer = new TextRenderer();
col3.setCellRenderer(renderer);
col3.setPreferredWidth(350);
CellRenderer cellRender = new CellRenderer();
TableColumn col4 = jTable1.getColumnModel().getColumn(3);
col4.setCellEditor(jTable1.getDefaultEditor(Boolean.class));
col4.setCellRenderer(cellRender);
col4.setPreferredWidth(50);
TableButton buttonEditor = new TableButton("Button");
buttonEditor.addTableButtonListener(new TableButtonListener() {
//#Override
public void tableButtonClicked(int row, int col) {
RemarkDropDownList rmk = new RemarkDropDownList(noJob, row);
rmk.setVisible(true);
//userRemark1[row] = RemarkDropDownList.userOthersReamrk;
//String test = RemarkDropDownList.userOthersReamrk;
}
});
TableColumn col5 = jTable1.getColumnModel().getColumn(4);
col5.setCellRenderer(buttonEditor);
col5.setCellEditor(buttonEditor);
TableColumn col6 = jTable1.getColumnModel().getColumn(5);
col6.setCellEditor(jTable1.getDefaultEditor(Boolean.class));
col6.setCellRenderer(jTable1.getDefaultRenderer(Boolean.class));
col6.setPreferredWidth(50);
jTable1.setShowGrid(true);
jTable1.setGridColor(Color.BLACK);
jTable1.setAutoCreateRowSorter(true);
}
In my JTable I've created a button in column 5 like this.
TableButton buttonEditor = new TableButton("Button");
buttonEditor.addTableButtonListener(new TableButtonListener() {
//#Override
public void tableButtonClicked(int row, int col) {
RemarkDropDownList rmk = new RemarkDropDownList(noJob, row);
rmk.setVisible(true);
//userRemark1[row] = RemarkDropDownList.userOthersReamrk;
//String test = RemarkDropDownList.userOthersReamrk;
}
});
TableColumn col5 = jTable1.getColumnModel().getColumn(4);
col5.setCellRenderer(buttonEditor);
col5.setCellEditor(buttonEditor);
The button basically create a new JFrame with combobox inside it like this.
public class RemarkDropDownList extends javax.swing.JFrame {
public static String userOthersReamrk = "test";
private String userSelectedItem = "File Issue";
String jobno;
int rowNo;
public RemarkDropDownList() {
initComponents();
this.lblOthers.setVisible(false);
this.txtOthers.setVisible(false);
}
public RemarkDropDownList(String jobNo, int row) {
initComponents();
this.lblOthers.setVisible(false);
this.txtOthers.setVisible(false);
this.jobno = jobNo;
this.rowNo = row;
}
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JComboBox cb = (JComboBox)evt.getSource();
userSelectedItem = (String)cb.getSelectedItem();
if(userSelectedItem.equalsIgnoreCase("others"))
{
this.lblOthers.setVisible(true);
this.txtOthers.setVisible(true);
}
else
{
this.lblOthers.setVisible(false);
this.txtOthers.setVisible(false);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(userSelectedItem.equalsIgnoreCase("others"))
{
userOthersReamrk = txtOthers.getText().toString();
if(userOthersReamrk == null || userOthersReamrk.equalsIgnoreCase(""))
{
JOptionPane.showMessageDialog(null, "Please enter Remark");
}
}
else
{
userOthersReamrk = userSelectedItem;
//String [] remark = new String [1000];
///remark[rowNo] = userOthersReamrk;
ReportPanelMin rpm = new ReportPanelMin();
//rpm.userRemark1[rowNo] = remark[rowNo];
rpm.refTable(jobno);
this.setVisible(false);
}
}
}
Everything is working, but the last part. I've created a static global variable (userOthersReamrk) in RemarkDropDownList class (the new class) to hold user drop down selected value. I call the refTable function again to reload the table so i can assign the userOthersReamrk value to column no 7 like this userRemark = new String[sortedMap.size()];. When i debug, I can see the user selected value is assigned touserRemark array but its not population in the table. The column showing the default value test which i decalred in RemarkDropDownList. I know the code is so long, but i post everything to give better understanding on what im doing. What/where i need to make change so my user's selected value is shown in column 7 instead the default value.

Unable to populate table with data from database

I have problem when trying to fetch the data from database and display in database. I get from user input and store as a search variable. This is how I set up my table:
//I get the user input to perform search
#FXML
public void searchResident(ActionEvent event){
String search=getTb_search().getText();
if(search.equals("")){
Dialogs.showErrorDialog(null, "Please enter something", "Blank fields detected", "");
}else{
setUpSearchTable(search);
}
}
//How I set up my table
public void setUpSearchTable(String search) {
TableColumn rmNameCol = new TableColumn("Name");
rmNameCol.setVisible(true);
rmNameCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<SearchNeedyResidentController, String>, ObservableValue<String>>() {
public ObservableValue<String> call(TableColumn.CellDataFeatures<SearchNeedyResidentController, String> p) {
return p.getValue().searchNameProperty();
}
});
TableColumn rmNricCol = new TableColumn("NRIC");
rmNricCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController, String>("search_nric"));
rmNricCol.setMinWidth(150);
TableColumn rmPhNoCol = new TableColumn("Phone Number");
rmPhNoCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController,String>("search_phNo"));
rmPhNoCol.setMinWidth(350);
TableColumn rmIncomeCol = new TableColumn("Income($)");
rmIncomeCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController, String>("search_income"));
rmIncomeCol.setMinWidth(100);
ResidentManagement.entity.NeedyResidentEntity searchValue= new ResidentManagement.entity.NeedyResidentEntity();
//viewProduct.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table_search.setEditable(false);
table_search.getColumns().addAll(rmNricCol, rmNameCol, rmIncomeCol, rmPhNoCol);
table_search.getItems().setAll(searchValue.searchResident(search));
}
}
//How I populate the table data
public List<SearchNeedyResidentController> searchResident(String search){
List ll = new LinkedList();
try {
DBController db = new DBController();
db.getConnection();
String sql = "SELECT * FROM rm_needyresident WHERE name LIKE '" + search + "%'";
ResultSet rs = null;
// Call readRequest to get the result
rs = db.readRequest(sql);
while (rs.next()) {
String nric=rs.getString("nric");
String name = rs.getString("name");
double income = rs.getDouble("familyIncome");
String incomeStr = new DecimalFormat("##.00").format(income);
String phNo = rs.getString("phNo");
SearchNeedyResidentController row = new SearchNeedyResidentController();
row.setSearchNric(nric);
row.setSearchName(name);
row.setSearchIncome(incomeStr);
row.setSearchPhNo(phNo);
ll.add(row);
}
rs.close();
} catch (SQLException ex) {
ex.printStackTrace();
System.out.println("Error SQL!!!");
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
return ll;
}
}
When search button is on click, the table column is displayed. However, it's just show a blank table even though there's matching result. I debug already and I think the error is at the retrieving data in the searchResident method. It's not retriving the data from database. Anybody know what's wrong?
Thanks in advance.
try dis one...
#FXML private void SearchButton()
{
Connection c ;
datamem = FXCollections.observableArrayList();
try
{
c = Dao.getCon();
String SQL =SELECT * FROM `Member`;
ResultSet rs = c.createStatement().executeQuery(SQL);
if(table.getColumns().isEmpty())
{
for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++)
{
final int j = i;
TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1));
col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){
public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
table.getColumns().addAll(col);
}//for
}//if
while(rs.next())
{
ObservableList<String> row = FXCollections.observableArrayList();
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++)
{
row.add(rs.getString(i));
}// for
datamem.add(row);
}//while
table.setItems(datamem);
}//try
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Problem in Search Button "+e);
}
}//else
}//else
} //search method