MoveNext for List - c#

I'm trying to create an application where you press the next button and it shows the next object in a list. In this case an object of Employee, I'm using Linq To SQL. I've read about MoveNext, but I don't know how it works and I tried something else which doesn't work (code below). Basically I want to have a next/previous button to get employees from the db.
Here's the code to get all Employees:
public List<Employee> GetEmployees()
{
var q =
from a in db.GetTable<Employee>()
select a;
List<Employee> employeeList = q.ToList();
return employeeList;
}
Button click:
private void btnNext_Click(object sender, EventArgs e)
{
Increment();
LoadEmployee();
}
Increment (method) (this is my solution for getting the next object, but it isn't optimal at all):
public void Increment()
{
if (con.GetEmployee(id) != null)
{
id++;
}
else
{
id += 2;
}
}
LoadEmployee (method):
public void LoadEmployee()
{
Employee e = con.GetEmployees().FirstOrDefault(f => f.id.Equals(id));
tbId.Text = e.id.ToString();
tbFname.Text = e.Fname;
tbLname.Text = e.Lname;
tbDate.Text = e.Date;
}

Sir, try this
public void LoadEmployee()
{
Employee e = con.GetEmployees();
tbId.Text = e[id].id.ToString();
tbFname.Text = e[id].Fname;
tbLname.Text = e[id].Lname;
tbDate.Text = e[id].Date;
}
use id as an index of your collection

So to summarise:
You're using SQL
And want to take a record with 'next' / 'prev'.
If you look at SQL itself without using cursors, I'd say that translates as a 'skip' and 'take 1'. Linq has these features:
// initialize index
int x = -1;
// move next:
var currentEmployee = context.Employees.Skip(++x).FirstOrDefault();
if (currentEmployee == null)
{
// End.
}
// move prev:
if (--x < 0)
{
// move back past start
x = 0;
}
var currentEmployee = context.Employees.Skip(x).FirstOrDefault();
if (currentEmployee == null)
{
// No elements
}

Related

I have SQLite db with 3 rows, when i delete data from row, data will lost but row will still, how can i delete that blank row?

I have xamarin app and I am using SQLite for saving data, if I have 3 rows and delete second row, then data will delete but row will be blank and its still here and problem is, that I need to load one column from every row. I am using for cycle and count to set maximum for it. But count says I have two rows so for cycle load just first and not second because second is on third line and second is blank.
I need to delete blank rows or to discover another solution how to load it. How can i delete blank DB?
Counting algorythm:
public int GetNumberPhotos()
{
var db = new SQLiteConnection(_dbPath);
db.CreateTable<Airplane>();
int count = 0;
if (db.Table<Airplane>().FirstOrDefault(l => l.Id == 1) != null)
count = db.Table<Airplane>().Count();
return count;
}
loading:
public int BetterUniReg()
{
int numberPhotos = GetNumberPhotos();
string[] allReg = new string[numberPhotos];
string[] uniReg = new string[numberPhotos];
int uniRegCnt = 0;
var db = new SQLiteConnection(_dbPath);
//db fill
for (int i = 0; i <= numberPhotos; i++)
{
if (db.Table<Airplane>().FirstOrDefault(b => b.Id == i) != null)
{
var rowData = db.Table<Airplane>().FirstOrDefault(c => c.Id == i);
i--;
allReg[i] = rowData.Registration;
i++;
}
}
Here is delete code:
private async void deleteButton_Clicked(object sender, EventArgs e)
{
var action = await DisplayAlert("Delete", "Do you want delete picture?", "Cancel", "Delete");
if (action)
{
}
else
{
var butto = sender as Button;
var frame = butto.Parent.Parent.Parent.Parent as Frame;
await frame.FadeTo(0, 600);
var button = (Button)sender;
var plane = (Airplane)button.BindingContext;
var db = new SQLiteConnection(_dbPath);
db.Delete<Airplane>(plane.Id);
Refresh();
}
}
I have done walkaround by adding if its last row and its null then do one more cycle.
Here is code:
for (int i = 1; i <= numberPhotos; i++)
{
if (db.Table<Airplane>().FirstOrDefault(c => c.Id == i) != null)
{
var rowData = db.Table<Airplane>().FirstOrDefault(c => c.Id == i);
allReg[regnumber] = rowData.Registration;
regnumber++;
}
if (db.Table<Airplane>().FirstOrDefault(c => c.Id == i) == null && i == numberPhotos)
{
numberPhotos = numberPhotos + 1;
}
}

Variable in other function has always value zero

I have problem with one variable.
protected void godziny_Click(object sender, EventArgs e)
{
var id_filmu = Request["id"];
var data = Request["data"];
var godzina = TimeSpan.Parse(hidden2.Value);
var query = from h in bazaDC.seanses
where h.godzina == godzina && h.id_filmu == int.Parse(id_filmu) && h.data == DateTime.Parse(data)
select h;
foreach (var a in query)
{
Session["id_seansu"] = a.id_seansu;
}
}
id_seansu is declared outside function, just in partial class. I have to get that variable in another function:
protected void rezerwujButton_Click(object sender, EventArgs e)
{
DateTime dzisiejszaData = DateTime.Today;
TimeSpan godzinaRezerwacji = DateTime.Now.TimeOfDay;
DateTime dataZarezerwowania;
TimeSpan czasZarezerwowania;
var query = from wszystkieRezerwacje in bazaDC.rezerwacjes
select wszystkieRezerwacje;
foreach(var i in query)
{
if(i.data_rezerwacji.HasValue && i.czas_rezerwacji.HasValue)
{
dataZarezerwowania = i.data_rezerwacji.Value;
czasZarezerwowania = i.czas_rezerwacji.Value;
}
}
rezerwacje nowaRezerwacja = new rezerwacje();
if (Session["id_seansu"] != null)
{
Response.Write(Session["id_seansu"]);
};
/*nowaRezerwacja.imie_klienta = imieTextBox.Text;
nowaRezerwacja.nazwisko_klienta = nazwiskoTextBox.Text;
nowaRezerwacja.email_klienta = emailTextBox.Text;
nowaRezerwacja.nrtel_klienta = nrKomTextBox.Text;
nowaRezerwacja.numer_miejsca = Hidden1.Value;
nowaRezerwacja.data_rezerwacji = dzisiejszaData;
nowaRezerwacja.czas_rezerwacji = godzinaRezerwacji;
nowaRezerwacja.id_seansu = id_seansu;
bazaDC.rezerwacjes.InsertOnSubmit(nowaRezerwacja);
bazaDC.SubmitChanges();*/
}
But when I wanna write that variable by Response.Write("id_seansu") in rezerwujButton_Click It is always "0".
But when I wanna write it in godziny_Click It have correct value.
Why variable is getting 0 value in another function?
When you perform the first click, the page will post back and hence the value of the variable get reset, to Persist Variable on Postback you have to use either session or ViewState, if the you want this variable in other pages then you can go ahead with session if it is specifically for this page then you have to opt ViewState. You can assign like this:
ViewState.Add("id_seansu","some value");
And get value like this:
if (ViewState["id_seansu"] != null)
{
var id_seansu = ViewState["id_seansu"];
}

I Need to insert Exception details into sql server database

My issue is that i have an aspx page which is having try and catch bocks in its code file which will handle exception using exception object in catch,now when the program execution reaches this catch block it calls the public method GetExceptionDetails which will return a long string text containing the values of all the properties of exception but not property's name in it.Now when i insert the properties values into table object's field of database everything is right upto the point when the code reaches at db.submitchanges(),in which an exception statement pops out which reads sqldatetimeoverflow and under sqltypesexception.Please help me figure out the issue in this,Below is the whole code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication5
{
public partial class EnterMarks : System.Web.UI.Page
{
public float average,total;
public string grade,chk,exmessage;
DataClasses1DataContext db = new DataClasses1DataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["StudentID"] != null)
{
Label1.Text = Request.QueryString["StudentID"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
List<int> stdID = new List<int>();
tblGrade tb = new tblGrade();
total = (float)(Convert.ToDouble(TextBox1.Text) + Convert.ToDouble(TextBox2.Text) + Convert.ToDouble(TextBox3.Text));
average = total / 3;
if (average > 85 && average < 90)
{
grade = "AA";
}
else if(average>80 && average<85)
{
grade = "A";
}
else if (average > 75 && average < 80)
{
grade = "BB";
}
else if (average > 70 && average < 75)
{
grade = "B";
}
else if (average > 65 && average < 70)
{
grade = "C";
}
else if (average > 60 && average < 65)
{
grade = "CC";
}
else if (average > 55 && average < 60)
{
grade = "D";
}
else
{
grade = "DD";
}
//var query = from m in db.tblGrades
// where m.StudentID == Convert.ToInt32(Request.QueryString["StudentID"])
// select m;
// foreach (var q in query)
//{
tb.StudentID = Convert.ToInt32(Request.QueryString["StudentID"]);
tb.Grade = grade;
db.tblGrades.InsertOnSubmit(tb);
db.SubmitChanges();
Response.Redirect("WebForm1.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
//var query1 = from n in db.tblContacts where n.StudentID == int.Parse(TextBox4.Text) select n;
tblExcDet te = new tblExcDet();
var query1 = from n in db.tblContacts select n.StudentID;
//try
//{
foreach (var q in query1)
{
if (q.Equals((int.Parse(TextBox4.Text))))
{
Label2.Text = "ID Found";
}
}
try
{
int? i = null;
tblContact tc = new tblContact();
tc.StudentID = (int)i ;
//db.tblContacts.InsertOnSubmit(tc);
db.SubmitChanges();
}
catch (Exception ex)
{
exmessage = GetExceptionDetails(ex);
te.ExMessage = exmessage.Split('*')[0];
te.ExData = exmessage.Split('*')[1];
te.ExInner = exmessage.Split('*')[2];
te.ExTargetSite = exmessage.Split('*')[3];
te.ExStackTrace = exmessage.Split('*')[4];
te.ExHelplink = exmessage.Split('*')[5];
te.ExSource = exmessage.Split('*')[6];
te.ExHresult = exmessage.Split('*')[7];
db.tblExcDets.InsertOnSubmit(te);
db.SubmitChanges();
Label2.Text = "Can't assign null value into a table id";
}
}
//public static string GetExceptionDetails(Exception ex)
//{
// var properties = ex.GetType().GetProperties();
// var fields = properties.Select(property=>new{
// name = property.Name,value = property.GetValue(ex,null)
// }).Select(x => String.Format(
// "{0} = {1}",
// x.name,
// x.value != null ? x.value.ToString() : String.Empty
// ));
// return String.Join("*", fields);
//}
public static string GetExceptionDetails(Exception ex)
{
var properties = ex.GetType().GetProperties();
var fields = properties.Select(property => new
{
name = property.Name,
value = property.GetValue(ex, null)
}).Select(x => String.Format(
"{0}",
x.value != null ? x.value.ToString() : String.Empty
));
return String.Join("*", fields);
}
}
}
Also here i'm using LINQ structure to insert data into sql server database.
Do you have the field set as autogenerated in the designer? If that's not the problem, I'd suggest setting up logging of the data context actions to the console and checking the actual SQL generated to make sure that it's inserting that column, then trace backward to find the problem.
context.Log = Console.Out;
FWIW, I often set my "CreatedTime" and "LastUpdatedTime" columns up as autogenerated (and readonly) in the designer and give them a suitable default or use a DB trigger to set the value on insert or update. When you set it up as autogenerated, it won't include it in the insert/update even if modified. If the column doesn't allow nulls, then you need to supply an alternate means of setting the value, thus the default constraint and/or trigger.
You might also want to try an explicit cast to
SqlDbType.DateTime
before doing updatechanges

How can I delete every item in my list?

How do I remove everything on my listview with my clickfunction below?
Now it only removes the first item in the list and not every item.
This is my code:
async void OnButtonClickedRemoveEverything (object sender, EventArgs args)
{
theGuestListMembers ourItem = null; //theGuestListMembers is our Class.
foreach (theGuestListMembers c in ourEventList) { //oureventlist = this is Our List.
ourItem = c;
}
// . listID is a public string that gets the personal "info" from a user (the objectID). so I guess the "ourItem.listID" is our problem because I only get 1 persons objectID i guess not everyone from the list?
if(ourItem != null)
{
parseAPI.deleteTheGuestList
(Application.Current.Properties ["sessionToken"].ToString (), ourItem.listID);
ourEventList.Remove (ourItem);
EmployeeList.ItemsSource = null; //name of our list
EmployeeList.ItemsSource = ourEventList;
}
Navigation.PopAsync ();
}
My database where i get info.
var getItems = await parseAPI.getOurGuestList (Application.Current.Properties ["sessionToken"].ToString (), owner);
EmployeeList.ItemsSource = null;
ourEventList = new List<theGuestListMembers> ();
foreach (var currentItem in getItems["results"]) {
ourEventList.Add (new theGuestListMembers () {
listID = currentItem ["objectId"].ToString (),
theHeadName = currentItem ["YourName"].ToString ()
});
}
If you simply want to remove the items from the list, you can use ourEventList.Clear() or ourEventList.RemoveAll(ourItem => ourItem != null)
If you want to do something fancier, you can use this function:
private bool removeItem(theGuestListMember ourItem)
{
if (ourItem == null) return false;
parseAPI.deleteTheGuestList(ourItem);
return true;
}
And use it like this:
async private void OnButtonClickedRemoveEverything(object sender, EventArgs e)
{
ourEventList.RemoveAll(ourItem => removeItem(ourItem);
EmployeeList.ItemsSource = ourEventList;
Navigation.PopAsync ();
}

Datagridview sorting column based on matching string

I have a datagridview that I would like to have rows sorted based on the portion of a string entered from a user. The entered string is compared with all of the strings in a particular column. For instance, if I gave "comp" as the search word, the program would try to compare the search word with the strings on first column and sort the rows in a descending order which starts with "comp", such as "compare", "composition", "computer" etc. Rest of the words that do not match is either left alone or sorted in an alphabetical order (whichever is easier).
In LINQ, I am aware that you can apply the following code to achieve what you wanted with a string array:
var sortedWords = words.Where(x => x.Contains("comp"))
.OrderByDescending(x => x);
How can I achieve the same thing in Datagridview as I need to have the rows sorted, not just the items inside a particular column?
Edit:
The following code is giving a System.InvalidOperationException. (SetCurrentCellAddressCore is being called twice)
private void DGVPointCtrl_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
MatchComparer mc = new MatchComparer();
DGVPointCtrl.Sort(mc); //Error
}
I'm probably doing something wrong but I'm not sure why. Here is the code that programatically adds the rows for testing purposes:
private void BtnRefresh_Click(object sender, EventArgs e)
{
try
{
DGVPointCtrl.Rows.Clear();
int mainIndex = CmbMainDevice.SelectedIndex;
int subIndex = CmbSubDevice.SelectedIndex;
DDCDAO ddcdao = new DDCDAO(DDCGlobal.ddcEngineIP, ddc.Ip);
string pointListType;
object rs;
//Currently only supports IO DDC Request
//TO DO: Change DDCDAO to send proper subdevice requests
if (mainIndex == 0) //IO
{
#region Main Device: IO
}
//First row is for searching items
DGVPointCtrl.Rows.Add(new DataGridViewRow());
for (int i = 1; i < 5; i++)
{
DGVPointCtrl.Rows.Add(new DataGridViewRow());
DGVPointCtrl.Rows[i].ReadOnly = true;
}
DGVPointCtrl.Columns[0].SortMode = DataGridViewColumnSortMode.Programmatic;
DGVPointCtrl.Rows[0].DefaultCellStyle.Font =
new Font(DGVPointCtrl.DefaultCellStyle.Font, FontStyle.Italic | FontStyle.Bold);
if (subIndex == 1) //BI
{
PointDGVColumnGenerate("IO_BI");
}
else if (subIndex == 2) //BO
{
PointDGVColumnGenerate("IO_BO");
}
else if (subIndex == 3) //AI
{
PointDGVColumnGenerate("IO_AI");
}
else if (subIndex == 4) //AO
{
PointDGVColumnGenerate("IO_AO");
}
DGVPointCtrl.Rows[1].Cells[0].Value = "IO12314";
DGVPointCtrl.Rows[2].Cells[0].Value = "IO21948";
DGVPointCtrl.Rows[3].Cells[0].Value = "IO28194";
DGVPointCtrl.Rows[4].Cells[0].Value = "VP12984";
DGVPointCtrl.Rows[2].Cells[1].Value = "asdf";
#endregion
}
catch
{
}
}
private void PointDGVColumnGenerate(string key)
{
int colCount = 0;
DGVColumnTable.Clear();
for (int i = 0; i < COL_MAX; i++)
{
DGVPointCtrl.Columns[i].HeaderText = " ";
DGVPointCtrl.Columns[i].Visible = true;
}
foreach (string s in UIConstant.DDCPCtrlListColumnText[key])
{
DGVPointCtrl.Columns[colCount].HeaderText = s;
DGVColumnTable.Add(DGVPointCtrl.Columns[colCount]);
colCount++;
}
}
Edit2:
public class MatchComparer : IComparer
{
private static IComparer defaultComparer = new CaseInsensitiveComparer();
int IComparer.Compare(object x, object y)
{
DataGridViewRow xr = (DataGridViewRow)x;
DataGridViewRow yr = (DataGridViewRow)y;
string xs = "";
string ys = "";
try
{
xs = xr.Cells[0].Value.ToString();
}
catch
{
}
try
{
ys = yr.Cells[0].Value.ToString();
}
catch
{
}
if (HasMatch(xs) && !HasMatch(ys)) return -1;
else if (!HasMatch(xs) && HasMatch(ys)) return 1;
else return defaultComparer.Compare(xs, ys);
}
This is possible only if you are populating the grid yourself as opposed to binding it to the database.
Set DataGridViewColumn.SortMode to Programmatic.
Use DataGridView.Sort to impose a comparer like this:
public class MatchComparer : IComparer {
int IComparer.Compare(object x, object y) {
if (HasMatch(x) && !HasMatch(y)) return -1;
else if (!HasMatch(x) && HasMatch(y)) return 1;
else return defaultComparer.Compare(x, y);
}
private bool HasMatch(object x) {
return x is string && ((string)x).StartsWith("comp");
}
private static IComparer defaultComparer = new CaseInsensitiveComparer();
}

Categories