Windows Forms database auto generate ID column using LINQ - c#

Created an application to insert data into the database using LINQ. I kept the ID column in the database. I am looking for guidance on how to have the ID column automatically add the next ID number each time a new entry is made into the data base?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Week4_2_
{
public partial class Form1 : Form
{
LinqsqlinsertdataDataContext objcontxt = new LinqsqlinsertdataDataContext();
public Form1()
{
InitializeComponent();
}
private void buttonInsert_Click(object sender, EventArgs e)//Inserts Records
{
using (objcontxt = new LinqsqlinsertdataDataContext())
{
TblSoccer name = new TblSoccer
{
FirstName = txtFirstName.Text,
LastName = textBox2.Text,
Address = textBox1.Text,
Id = textBoxID.Text
};
objcontxt.TblSoccers.InsertOnSubmit(name);
objcontxt.SubmitChanges();
}
getAllRecords();
}
private void getAllRecords() //Show all records
{
using (objcontxt = new LinqsqlinsertdataDataContext())
{
dataGridView1.DataSource = objcontxt.TblSoccers;
}
}
private void Form1_Load(object sender, EventArgs e)
{
getAllRecords();
}
}
}

In LinqToSQL, it requires primary key to insert or update the row in the Table. So your ID Column will be PK and Identity auto incremented column.
In DBML, you have to select your ID Column go to properties and set below properties:
Auto Generated Value : true and Auto-Sync : OnInsert

Related

Deleting list items with SwipeView in Xamarin

I've made a contacts app in Xamarin and wanted to incorporate the SwipeView, but I can't figure out how to delete single contacts from my list. Any help?
using System;
using System.Collections.Generic;
using SQLite;
using System.Linq;
using Contacts.Classes;
using Xamarin.Forms;
using System.Diagnostics;
namespace Contacts
{
public partial class ContactsPage : ContentPage
{
public ContactsPage()
{
InitializeComponent();
Device.SetFlags(new[] {"SwipeView_Experimental"});
}
void NewContactToolbarItem_Clicked(System.Object sender, System.EventArgs e)
{
Navigation.PushAsync(new MainPage());
}
protected override void OnAppearing()
{
base.OnAppearing();
using(SQLiteConnection conn = new SQLiteConnection(App.FilePath))
{
conn.CreateTable<Contact>();
var contacts = conn.Table<Contact>().ToList();
contactsListView.ItemsSource = contacts;
Command DeleteCommand = new Command<Contact>(contact => { conn.Delete(contact); });
}
}
As Jason said, create a database access class include connection, deleting operation and so on. You could check the database access class in the link below: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/databases#data-manipulation-methods
Choose the Item you want to delete and invoke the delete method of SQLite database.
conn.DeleteAsync(item);
After deleting the Item, use the code below to get the list of database and reset the ItemSource.
conn.Table<Contact>().ToListAsync();
You could download the source file from the link below:
https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/todo/

Select printer name without showing PrintDialog

I have this code. When I need to print my report, it shows me a Print Dialog. I want to select my print name by code, and print my report without showing PrintDialog.
This is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Printing;
namespace POS.Reports
{
public partial class ProductsReceiptPreview : Form
{
BindingSource _data;
string _total, _cashr, _cashc;
public ProductsReceiptPreview(BindingSource data, string total,
string cashr, string cashc)
{
InitializeComponent();
_total = total; _cashr = cashr; _cashc = cashc;
_data = data;
}
private void ProductsReceipt_Load(object sender, EventArgs e)
{
DataReceiptBindingSource.DataSource = _data;
Microsoft.Reporting.WinForms.ReportParameter[] param = new
Microsoft.Reporting.WinForms.ReportParameter[]
{
new Microsoft.Reporting.WinForms.ReportParameter("ptotal",
_total),
new Microsoft.Reporting.WinForms.ReportParameter("pcashr",
_cashr),
new Microsoft.Reporting.WinForms.ReportParameter("pcashc",
_cashc),
new Microsoft.Reporting.WinForms.ReportParameter
("pdate",DateTime.Now.ToString())
};
this.rptProductsReceipt.LocalReport.SetParameters(param);
this.rptProductsReceipt.RefreshReport();
this.rptProductsReceipt.ZoomMode =
Microsoft.Reporting.WinForms.ZoomMode.PageWidth;
}
private void btnReports_Click(object sender, EventArgs e)
{
rptProductsReceipt.PrintDialog();
}
}
}
i never use your method but i use this
rptProductsReceipt.PrintToPrinter(1, false, 0, 0);
after using adapter and data table

Creating a 3 Form C# application.

A project that I received from school has simple instructions: Create a working 3 form C# application. I decided to create a form which will let the user choose from 3 different options (In this case: 1 ticket, 2 tickets, and 3 tickets). Then it will switch to a 2nd form and also let the user choose from 3 options (In this case: 1 bag of popcorn, A large soda, and a bag of chips). The Problem I am having is when it tries to display the total cost its always ends up being 0. I would really appreciate any help.
Code:
Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WongGregory9_part3ThreeForms
{
public partial class movieForm : Form
{
public movieForm()
{
InitializeComponent();
}
private void exitButton_Click(object sender, EventArgs e)
{
//Close form
this.Close();
}
private void displayButton_Click(object sender, EventArgs e)
{
//create a variable named snack for snackForm
snackForm snack = new snackForm();
//show the form snack
snack.ShowDialog();
}
}
Form2(snackForm):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WongGregory9_part3ThreeForms
{
public partial class snackForm : Form
{
//define varible ticket as 50
int ticket = 50;
//define varible twoTicket as 90
int twoTickets = 90;
//define varible threeTicket as 130
int threeTickets = 130;
//define varible popcorn as 65
int popcorn = 65;
//define varible soda as 30
int soda = 30;
//define varible chips as 40
int chips = 40;
//define varible ticketCost
int ticketCost;
//define varible snackCost
int snackCost;
//define varible totalCost;
int totalCost;
//create a variable named movie for movieForm
movieForm movie = new movieForm();
public snackForm()
{
InitializeComponent();
}
private void snackForm_Load(object sender, EventArgs e)
{
//if ticketRadioButton is checked then..
if (movie.ticketRadioButton.Checked)
{
//ticketCost = ticket
ticketCost = ticket;
}
//if ticketRadioButton2 is checked then..
if (movie.ticketRadioButton2.Checked)
{
//ticketCost = twoTicket
ticketCost = twoTickets;
}
//if ticketRadioButton3 is checked then..
if (movie.ticketRadioButton3.Checked)
{
//ticketCost = threeTicket
ticketCost = threeTickets;
}
//if popcornRadioButton is checked then..
if (popcornRadioButton.Checked)
{
//snackCost = popcorn
snackCost = popcorn;
}
//if sodaRadioButton is checked then..
if (sodaRadioButton.Checked)
{
//snackCost = soda
snackCost = soda;
}
//if chipsRadioButton is checked then..
if (chipsRadioButton.Checked)
{
//snackCost = chips
snackCost = chips;
}
}
private void button1_Click(object sender, EventArgs e)
{
//close form
this.Close();
}
private void displayButton_Click(object sender, EventArgs e)
{
//create a variable named movie for movieForm
displayForm display = new displayForm();
//totalCosts equals ticketCost plus snackCost
totalCost = ticketCost + snackCost;
//display totalCost to displayLabel
display.displayLabel.Text = totalCost.ToString();
//show the dialog entered into displayForm
display.ShowDialog();
}
}
Form3(displayForm):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WongGregory9_part3ThreeForms
{
public partial class displayForm : Form
{
public displayForm()
{
InitializeComponent();
}
}
Yup, two issues I can see, both in snackForm:
As per Sergey's comment, you are creating a new instance of movieForm, which doesn't know anything about the data on the original movieForm instance. You need to pass data from the original movieForm to your snackForm, in the same way as you pass the total cost from snackForm to displayForm.
You are checking the radio button selections in snackForm while the form is loading, i.e. before the user has had a chance to click them. Move these checks into snackForm.displayButton_Click

How do I make my DataGridView read info of a text file C#

so my issue is that, I can´t make my DataGridView read information from a text file already created, don´t know what to do really, I am kinda new to C#, so I hope you can help me :D
Here is my code to save the values from my grid:
private void buttonGuardar_Click(object sender, EventArgs e)
{
string[] conteudo = new string[dataGridView1.RowCount * dataGridView1.ColumnCount];
int cont = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
conteudo[cont++] = cell.Value.ToString();
}
}
File.WriteAllLines("dados.txt", conteudo);
And now, from a different form, there is another Grid that must be fill with the values saved in that File
The present code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication31
{
public partial class Form3 : Form
{
DateTime start, end;
private void Form3_Load(object sender, EventArgs e)
{
textBox1.Text = start.ToString("dd-MM-yyyy");
textBox2.Text = end.ToString("dd-MM-yyyy");
}
public Form3(DateTime s, DateTime e)
{
InitializeComponent();
start = s;
end = e;
}
}
}
In conclusion, both of the grid should have 4 Cells:
0-Designação
1-Grupo
2-Valor
3-Data
And the second one from Form3, should read the text file, in the right order
Hope you can help me, Thanks.
Please try this below.
I have exported the grid data in to a text file as same structure as how it appears in grid as below.
private void button1_Click(object sender, EventArgs e)
{
TextWriter writer = new StreamWriter("Text.txt");
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
for (int j = 0; j < DataGridView1.Columns.Count; j++)
{
writer.Write(DataGridView1.Rows[i].Cells[j].Value.ToString() + "\t");
}
writer.WriteLine("");
}
writer.Close();
}
Created a new class with properties as the column names and a method to load the exported data into a list collection of class as shown below.Here in this example ,my grid has two columns Name and Marks.so i declared those two properties in my user class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace WindowsFormsApplication1
{
public class User
{
public string Name { get; set; }
public string Marks { get; set; }
public static List<User> LoadUserListFromFile(string path)
{
var users = new List<User>();
foreach (var line in File.ReadAllLines(path))
{
var columns = line.Split('\t');
users.Add(new User
{
Name = columns[0],
Marks = columns[1]
});
}
return users;
}
}}
Now on the form load event of second form,call the above method and bind to the second grid as shown below
private void Form2_Load(object sender, EventArgs e)
{
dataGridView2.DataSource = User.LoadUserListFromFile("Text.txt");
}
Pleas mark this as answer,if it helps.

Winform BindingNavigator not saving item to database

I have designed a WinForm which is bound to my database using ADO.Net Entity Framework. On load my details form is populated with data from the database.
I can navigate through the items, however I can not add, save or update the item.
Below is the code for my form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
cpdEntities dbcontext;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dbcontext = new cpdEntities();
cpd_recipientsBindingSource.DataSource = dbcontext.cpd_recipients.ToList();
}
private void cpd_recipientsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
dbcontext = new cpdEntities();
dbcontext.SaveChanges();
}
}
}
Here is a simple example working with EntityFramework 4
How to Load:
using (var con = new cpdEntities())
{
cpd_recipientsBindingSource.DataSource = con.cpd_recipients.ToList();
}
How to Insert and Update:
if (cpd_recipientsBindingSource.Current == null) return;
using (var con = new cpdEntities())
{
var p = new Customer()
{
CustomerId = ((cpd_recipients)cpd_recipientsBindingSource.Current).Id,
CustomerIdNo = IdNoTextBox.Text,
CustomerName = CustomerNameTextBox.Text
};
var cus = new Customer();
if (p.CustomerId > 0)
cus = con.Customers.First(c => c.CustomerId == p.CustomerId);
cus.CustomerId = p.CustomerId;
cus.CustomerIdNo = p.CustomerIdNo;
cus.CustomerName = p.CustomerName;
if (p.CustomerId == 0)
con.Customers.AddObject(cus);
con.SaveChanges();
int i = cus.CustomerId;//SCOPE_IDENTITY
}
}
It looks like your re-instantiating your DbContext class in each of the events. Remove re-insantiating the DbContext from your saveItem event and give it a try again.

Categories