So here's my problem. I'm creating simple android app and I want to remove item from a List view. My code kind of works, the problem is that item is deleted after second click (remove button). Also i need to select item second time.
What I wanna do is to select an item one time, and delete it by clicking remove button.
Here is my code for Remove-button.
private void Remove_Activated(object sender, EventArgs e)
{
using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
{
conn.CreateTable<Book>();
var books = conn.Table<Book>().ToList();
booksListView.ItemsSource = books;
var selItem = (Book)booksListView.SelectedItem;
Book remBook = new Book()
{
Id = selItem.Id,
Name = selItem.Name,
Author = selItem.Author
};
conn.Delete(remBook);
};
}
I have also overrided OnAppearing(), can this be the problem?
protected override void OnAppearing()
{
base.OnAppearing();
Title = "Booklist";
using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
{
conn.CreateTable<Book>();
var books = conn.Table<Book>().ToList();
booksListView.ItemsSource = books;
}
}
I have done the adding part like this guy in this tutorial: https://www.youtube.com/watch?v=JhWwBOoqXQ8
Related
I am trying to come up with a solution where I can search items inside a combo box that contain certain word/phrase. I tried using the AutoComplete text box functionality, but that only searches for the first word which is no good to me.
I have followed the example provided at https://social.msdn.microsoft.com/Forums/vstudio/en-US/4c229a73-cdad-4fa3-95db-97f9ff7810c1/autocomplete-match-on-contains-not-startswith?forum=netfxbcl
I have initiated 2 lists
public List<string> listOnit = new List<string>();
public List<string> listNew = new List<string>();
I then load the data into a comboBox
if (rdr.HasRows == true)
{
// var source = new List<string>();
while (rdr.Read())
{
// myCollectionSales.Add(rdr[0].ToString());
listOnit.Add(rdr[0].ToString());
}
rdr.Close();
//textBox1.AutoCompleteCustomSource = myCollectionSales;
comboBox1.Items.AddRange(listOnit.ToArray());
}
and have a TextUpdate event handler to filter the list when text has changed
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
comboBox1.Items.Clear();
listNew.Clear();
foreach (var item in listOnit)
{
if (item.Contains(this.comboBox1.Text))
{
listNew.Add(item);
}
}
comboBox1.Items.AddRange(listNew.ToArray());
comboBox1.SelectionStart = this.comboBox1.Text.Length;
Cursor = Cursors.Default;
comboBox1.DroppedDown = true;
}
I am coming across a problem where the search results don't return what I expect. For example, I search for the string "Bud" and I only get the following results
http://prntscr.com/ppkatd
While in the database, there is also Budweiser 33cl and Keg Budweiser (http://prntscr.com/ppkbu4), for example, which is fetched on the first list.
Should I be using a different method, rather than "Contains"?
Perhaps you are using different cases?
Try with .ToLower():
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
comboBox1.Items.Clear();
listNew.Clear();
foreach (var item in listOnit)
{
if (item.ToLower().Contains(this.comboBox1.Text.ToLower()))
{
listNew.Add(item);
}
}
comboBox1.Items.AddRange(listNew.ToArray());
comboBox1.SelectionStart = this.comboBox1.Text.Length;
Cursor = Cursors.Default;
comboBox1.DroppedDown = true;
}
I am making a Windows Forms App that manages a hotel. It has Client, Room, Occupancy classes. Client and Rooms have an ArrayList that is populated at runtime from a .txt file that is then displayed in a clientListView and a roomDataGridView.
As such, I have this line of code to populate the roomsDGV:
roomsDGV.DataSource = roomsArrayList;
With the roomsDGV, I'm trying to add new Rows by clicking on the roomsDGV, like when it is NOT databound. I am also trying to edit the rows and save it to txt file after editing or as I'm editing. I can post more code as necessary but I'm not sure if showing more code will help at the current moment. In the end, I'm trying for a functionality so that I can highlight a client in the list and click on one of the rows in roomsDGV and assign that clientID to that room or any sort of way like that.
On load, the datagridview is loaded and formatted correctly from the arrayList but I seem to be having this problem of being able to edit the datagridview. It gives me this error when I click on one of the rows:
System.IndexOutOfRangeException: 'Index -1 does not have a value.'
This stems from Application.Run(new HotelManager());
Here is the form:
public partial class HotelManager : Form
{
// VARIABLES
string clientID;
// FILEPATHS
string clientsTxt = "Clients.txt";
string occupanciesTxt = "Occupancies.txt";
string roomsTxt = "Rooms.txt";
string clientsDat = "Clients.dat";
// ARRAYLIST FOR ROOMS and CLIENTS
ArrayList roomsArrayList = new ArrayList();
ArrayList clientsArrayList = new ArrayList();
//STACKS AND QUEUES INIT
// Load occupancies into stack > pop
Stack roomStack = new Stack();
Queue vacancyQueue = new Queue();
// RANDOM for ID
private readonly Random rand = new Random();
public HotelManager()
{
InitializeComponent();
}
private void HotelManager_Load(object sender, EventArgs e)
{
roomsDGV.DataSource = roomsArrayList;
// LOAD clients
// LoadClients();
RefreshClientList();
// LOAD rooms
LoadRooms();
}
private void NewClientButton_Click(object sender, EventArgs e)
{
AddClient();
}
private void checkInButton_Click(object sender, EventArgs e)
{
string clientID = clientList.SelectedItems[0].Text;
string[] text = File.ReadAllLines(occupanciesTxt);
foreach (string s in text)
{
if (s.Contains(clientID))
{
var replace = s;
Console.WriteLine(s);
replace = replace.Replace("false", "true");
}
}
File.WriteAllLines(occupanciesTxt, text);
}
// METHODS
private void AddClient()
{
//COLLECT DATA > CREATE NEW client > SHOW IN **PROGRAM/DataGridView** > add to clients file
// ID GENERATION > CHECKS AGAINST clientsTXT
clientID = rand.Next(0, 999999).ToString();
if (File.ReadLines(clientsTxt).Contains(clientID))
{
clientID = rand.Next(0, 999999).ToString();
}
Client client = new Client(clientID, firstNameBox.Text, lastNameBox.Text);
try
{
if (!string.IsNullOrWhiteSpace(phoneNumBox.Text))
{
client.PhoneNumber = Convert.ToInt64(phoneNumBox.Text);
}
if (!string.IsNullOrWhiteSpace(addressBox.Text))
{
client.Address = addressBox.Text;
}
}
catch (Exception)
{
MessageBox.Show("Please use the correct format!");
throw;
}
clientsArrayList.Add(client);
using (StreamWriter file =
new StreamWriter("Clients.txt", true))
{
file.WriteLine(client.ToString());
}
RefreshClientList();
// TEST CODE // SERIALIZATION TO .DAT
SerializeClientData(client);
}
private void LoadClients()
{
// LOADS arrayList FROM .txt FILE
List<string> clientList = File.ReadAllLines(clientsTxt).ToList();
foreach (var c in clientList)
{
Client client = new Client(c);
clientsArrayList.Add(client);
}
}
private void LoadRooms()
{
List<string> roomsList = File.ReadAllLines(roomsTxt).ToList();
foreach (var r in roomsList)
{
var roomDetails = r.Split('|');
if (r.Contains("BASIC"))
{
BasicRoom basic = new BasicRoom();
basic.RoomNumber = roomDetails[0];
basic.NumberOfBeds = Convert.ToInt32(roomDetails[1]);
basic.Balcony = Convert.ToBoolean(roomDetails[2]);
basic.DownForRepair = Convert.ToBoolean(roomDetails[3]);
basic.Smoking = Convert.ToBoolean(roomDetails[4]);
roomsArrayList.Add(basic);
}
else if (r.Contains("SUITE"))
{
Suite suite = new Suite();
suite.RoomNumber = roomDetails[0];
suite.NumberOfBeds = Convert.ToInt32(roomDetails[1]);
suite.Balcony = Convert.ToBoolean(roomDetails[2]);
suite.DownForRepair = Convert.ToBoolean(roomDetails[3]);
suite.NumberOfRooms = Convert.ToInt32(roomDetails[4]);
roomsArrayList.Add(suite);
}
}
roomStack = new Stack(roomsArrayList);
foreach (var item in roomStack)
{
Console.WriteLine(item);
}
}
private void RoomsDGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void RoomsDGV_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
}
}
So far I've looked through all the properties but I can't seem to find the right one. I know I can add/use comboboxes and etc to add a new item into the arrayList instead but I'm trying for datagridview functionality
I expect to edit and add rows to the DGV, but something in the designer is preventing me?
Here is the DGV, and clicking on any of the rows breaks it.
https://imgur.com/a/GG7ZwdV
check this
Insert, Update, Delete with DataGridView Control in C# (Windows Application) | A Rahim Khan's Blog
Insert, Update and Delete Records in a C# DataGridView
Good Luck
i have a dynamic list of client devices which will be added over the network. Once they are connected their details are save in JSON file.
I would like to have an additional display and control of the client device(s) where I click on a Add button with a MenuFlyout populated with the list of the client device(s)'s ClientName from the JSON file. Once the menuitem is selected, it will add a button and connection status indicator (eg. connected, disconnected or error) for the respective client device selected on a grid.
This is what I have did for adding the button but couldn't figure out how to bind to the JSON
Please help.
Thanks.
my json class is created in a separate .cs
I am not sure did I do it correctly at MenuFlyoutItem_Click where item.clientname has an error.
The json file clientslist.txt i have checked for the format it seems correct.
You can refer to following code. I have not found a way with using Binding or x:Bind,but we can add the MenuFlyoutItem to the MenuFlyout manually after the json data deserialized.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var deviceList = JsonConvert.DeserializeObject<List<DeviceInfo>>(jsonData);
var menuFlyout = new MenuFlyout();
foreach (var device in deviceList)
{
var menuFlyoutItem = new MenuFlyoutItem() { Name = device.DeviceName, Text = device.DeviceName };
menuFlyoutItem.Tag = device.DeviceName;
menuFlyoutItem.Click += MenuFlyoutItem_Click;
menuFlyout.Items.Add(menuFlyoutItem);
}
ButtonCreateDevice.Flyout = menuFlyout;
}
private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
{
var item = sender as MenuFlyoutItem;
var deviceName = item.DeviceName;
//TO DO SOMETHING
}
DeviceInfo class defined as:
class DeviceInfo
{
public string DeviceName { get; set; }
public string Status { get; set; };
}
Tested with the sample data(jsonData) as:
[{"DeviceName":"LED-1","Status":"Connected"},{"DeviceName":"LED-2","Status":"Connected"},{"DeviceName":"LED-3","Status":"Connected"}]
I manage to use serialization.json to do it
private async void AddButton_Click(object sender, RoutedEventArgs e)
{
List<ClientList> clientLists;
var jsonSerializer = new DataContractJsonSerializer(typeof(List<ClientList>));
try
{
var myStream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(CLIENTSLIST);
clientLists = (List<ClientList>)jsonSerializer.ReadObject(myStream);
var menuFlyout = new MenuFlyout();
foreach (var device in clientLists)
{
var menuFlyoutItem = new MenuFlyoutItem() { Name = device.clientname, Text = device.clientname };
menuFlyoutItem.Tag = device.clientname;
menuFlyoutItem.Click += MenuFlyoutItem_Click;
menuFlyout.Items.Add(menuFlyoutItem);
}
AddButton.Flyout = menuFlyout;
}
catch (Exception)
{
//Do nothing, file doesn't exist
}
}
private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
{
var item = sender as MenuFlyoutItem;
var deviceName = item.Tag;
//TO DO SOMETHING
}
}
I'm completely new to databases and EF but I made a database with EF and have a DataGridView control on a windows form that I made by dragging my datasource to my form. After the user enters their information and hits the save button it succesfully saves their information in the database using this code
public partial class bsMainPage : Form
{
BSDATAContainer db = new BSDATAContainer();
public bsMainPage()
{
InitializeComponent();
}
private void saveBtn_Click(object sender, EventArgs e)
{
BSRecords breakfastRecord = new BSRecords();
breakfastRecord.BS = brkBS.ToString();
breakfastRecord.Carbs = brkCarb.ToString();
breakfastRecord.Notes = brkftNoteTxt.Text;
breakfastRecord.Date = dateTxt.Text;
BSRecords lunchRecord = new BSRecords();
lunchRecord.BS = lchBS.ToString();
lunchRecord.Carbs = lchCarb.ToString();
lunchRecord.Notes = lnchNoteTxt.Text;
lunchRecord.Date = dateTxt.Text;
BSRecords dinnerRecord = new BSRecords();
dinnerRecord.BS = dnrBS.ToString();
dinnerRecord.Carbs = dnrCarb.ToString();
dinnerRecord.Notes = dnnrNoteTxt.Text;
dinnerRecord.Date = dateTxt.Text;
db.BSRecords.Add(breakfastRecord);
db.BSRecords.Add(lunchRecord);
db.BSRecords.Add(dinnerRecord);
db.SaveChanges();
}
}
But it doesn't show up in the database until I restart the program. When the user selects a row in the DataGridView and hits the delete button which has this code
private void deleteRowsBtn_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in this.bSRecordsDataGridView.SelectedRows)
{
bSRecordsDataGridView.Rows.RemoveAt(item.Index);
}
db.SaveChanges();
}
It deletes the data in the DataGridView but doesn't save the changes in my database. I have followed all the answers I found on here and other sites to delete in the database but nothing will save the deleted changes. Does anyone have any idea how to make it work?
You can delete it using remove. You will need to get the key/id field so without seeing the grid and assuming it is say in a hidden first column:
private void deleteRowsBtn_Click(object sender, EventArgs e)
{
string delId;
BSRecords deleteRecord;
foreach (DataGridViewRow item in this.bSRecordsDataGridView.SelectedRows)
{
bSRecordsDataGridView.Rows.RemoveAt(item.Index);
// code to remove record from database
delId = item.Cells[0].Value.ToString(); // column that has id field
deleteRecord = db.BSRecords.First(b => b.Id == delId); // get the record. will throw exception if not found.
db.BSRecords.Remove(deleteRecord);
}
db.SaveChanges();
bSRecordsDataGridView.DataBind(); // this will refresh your grid. Do same in save.
}
Also note you can rewrite this code:
BSRecords breakfastRecord = new BSRecords();
breakfastRecord.BS = brkBS.ToString();
breakfastRecord.Carbs = brkCarb.ToString();
breakfastRecord.Notes = brkftNoteTxt.Text;
breakfastRecord.Date = dateTxt.Text;
with an object initializer:
BSRecords breakfastRecord = new BSRecords { BS = brkBS.ToString(),
Carbs = brkCarb.ToString(),
Notes = brkftNoteTxt.Text,
Date = dateTxt.Text };
In this page, you can add items. now you press "Save" to add another one. Heres the code:
private void Btn_Save_Click(object sender, RoutedEventArgs e)
{
// Adding the item to DB and List
MainData.MainDataItem MDI_Temp = new MainData.MainDataItem();
MDI_Temp.Int_AF = Convert.ToInt32(Tb_AF.Text);
MDI_Temp.Int_HO = Convert.ToInt32(Tb_HO.Text);
MDI_Temp.Int_ST = Convert.ToInt32(Tb_ST.Text);
MDI_Temp.Int_STD = Convert.ToInt32(Tb_STD.Text);
MDI_Temp.Int_DIA = Convert.ToInt32(Tb_DIA.Text);
MDI_Temp.Int_ECK = Convert.ToInt32(Tb_ECK.Text);
MDI_Temp.Int_MID = ((HelperClasses.Main_VM)this.DataContext).MDO_TmpStore.Int_ID;
MDI_Temp.Str_Bauteil = Str_Bauteil;
MDI_Temp.Str_Defekt = Str_Defekt;
MDI_Temp.Str_Massnahme = Str_Massnahme;
MDI_Temp.Str_Feld = Tb_Feld.Text;
MDI_Temp.Str_Zeile = Tb_Zeile.Text;
MDI_Temp.Int_Pos = Convert.ToInt32(Tb_Pos.Text);
HelperClasses.SQL_Class.DBAddItem(MDI_Temp);
// Navigate
HelperClass.Navigate("pages/New_Item.xaml");
}
And this is the void in the helperclass:
public static void Navigate(string Str_Uri)
{
((MainWindow)Application.Current.Windows[0]).Fm_MainContainer.Source = new Uri(Str_Uri, UriKind.Relative);
}
The first time you click on Btn_Save the page reloads, the second time it onyl add the item
Another option is to create an overload of navigate in helper class
public static void Navigate(object target)
{
((MainWindow)Application.Current.Windows[0]).Fm_MainContainer.Content = target;
}
ans use this way
// Navigate
New_Item item = new New_Item();
HelperClass.Navigate(item);
this will ensure to have a new initialization every time