I´m using C# Windows forms application and i got 5 items in a checklistbox.
Now I have to save these items into a MS Access database table.
Does anyone knows how i should do it?
(Sprachen = checkedlistbox)
private void button1_Click_1(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO Employee (Vorname, Nachname, Wohnort, Geburtstag, Abteilung, Nummer, MKZ, Führerschein, Sprachen) values('" + Vorname.Text + "','" + Nachname.Text + "','" + Wohnort.Text + "','" + Geburtstag.Text + "','" + Abteilung.Text + "','" + Mitarbeiter.Text + "','" + MKZ.Text + "'," + Führerschein.Checked.ToString() + "," + Sprachen.SelectedItems + ")";
command.ExecuteNonQuery();
MessageBox.Show("Daten gespeichert!");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
everytime i tried it with toString(), it gives me an error:
For at least one required parameter no value was specified.
I can only count how many items i´ve checked in the checklistbox.
Anyone got an solution?
Sprachen.SelectedItems returns list of selected items. If you are trying to insert the items which are checked in checkedlistbox then you have to loop for checklistbox.CheckedItems.
Instead of "Sprachen.SelectedItems" pass checklistbox.CheckedItems[0].ToString() as value and check the code. Note: 0 is hard coded.. later you can loop it
String type value must be passed within single quote. Check out last two fields.
Related
This question already has answers here:
how to get the last record number after inserting record to database in access
(6 answers)
Closed 1 year ago.
Am working with Access as Database in C# (Visual Studio 15). I want to save form entries (add record) into the Access Database and would want the corresponding ID of the record to show in MsgBox upon a successful saving. I have tried the following:
private void Form21_Load(object sender, EventArgs e)
{
try
{
connection.Open();
checkConnection.Text = "Server Connection, Successful";
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error, Server not connected " + ex);
}
}
private void Button6_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into Students_File ([YourNames],[Nationality],[StateOfOrigin],[PlaceOfBirth],[DoB],[HomeAddress],[LastSchools1],[LastClass1],[LastSchools2],[LastClass2],[LastSchools3],[LastClass3],[AdmClass],[CurrentClass],[Guidian],[GuardianContact],[UserName],[PassWord],[Gender],[RegistrationDate]) values('" + YourNames.Text + "','" + Nationality.Text + "','" + StateOfOrigin.Text + "','" + PlaceOfBirth.Text + "','" + DoB.Text + "','" + HomeAddress.Text + "','" + LastSchools1.Text + "','" + LastClass1.Text + "','" + LastSchools2.Text + "','" + LastClass2.Text + "','" + LastSchools3.Text + "','" + LastClass3.Text + "','" + AdmClass.Text + "','" + CurrentClass.Text + "','" + Guidian.Text + "','" + GuardianContact.Text + "','" + UserName.Text + "','" + PassWord.Text + "','" + Gender.Text + "','" + RegistrationDate.Text + "')";
command.ExecuteNonQuery();
//MessageBox.Show("Congrats! Your registration, is successful. You may now click close button, then proceed to login");
command.CommandText = "Select * from Students_File where UserName='" + UserName.Text + "' and PassWord='" + PassWord.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Congrats! Your registration, is successful. You may now click close button, then proceed to login");
this.Close();
}
else if (count > 1)
{
MessageBox.Show("Sorry, the chosen username or password is currently existing or picked by another user. Consequently, your registration was not successful. Do please, decide another but a unique one. Thank you");
}
connection.Close();
}
You can do it this way:
using (OleDbCommand Command = new OleDbCommand("", conn))
{
Command.CommandText = "Your big ugly mess - need to change this to parmaters!)";
Command.Connection.Open();
Command.ExecuteNonQuery();
Command.CommandText = "Select ##Identity";
var intLastID = Command.ExecuteScalar;
MsgBox("Last id into database = " + intLastID);
}
As noted, you do want to change that insert command - it too long, too difficult to maintain, and subject to mistakes in code and even sql injection.
But, for now, you can use the above approach to get/pick up the last ID insert.
In solution to my inquiry, i have the following code (From Kevin):
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("#CategoryName", OleDbType.Integer);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
Now, my challenge is how do i get the ID to appear in messagebox after a successful record creation. Please consider my earliest code in this post in connection with this.
This question already has answers here:
a database error :"No value given for one or more required parameters."
(2 answers)
Closed 3 years ago.
I am trying to insert data into ms access
I have rechecked the code many times seems nothing wrong
private void registerbutton_Click(object sender, EventArgs e)
{
registerconnection.Open();
OleDbCommand insert = new OleDbCommand();
insert.Connection = registerconnection;
insert.CommandText = "insert into StudentDatabase (FirstName, LastName, DOB, City, State, Email, ContactNo, ContactNo2, Courses, Username, Password, DateRegister) values ('"+fnametextbox.Text+ "','" + lnametextbox.Text + "','" + dobtextbox.Text + "','" + citytextbox.Text + "','" + statetextbox.Text + "','" + emailtextbox.Text + "','" + ctcnotextbox.Text + "','" + ctcnotextbox2.Text + "','" + coursetextbox.Text + "','" + usernametextbox.Text + "','" + passwordtextbox.Text + "','" + registerdatetextbox.Text + "')";
insert.ExecuteNonQuery();
MessageBox.Show("Data inserted");
}
I expected it was able to insert the data but it turns out into an error
This shall help you...I did not test the code but i assume it will work.
http://dotnetsridhar.blogspot.com/2012/05/ma-access-database-for-windows-c.html
also check your textbox input value , some special character was a reserved character in SQL , example '; , if user type those special character on textbox and process by your current code logic , it may break because you try to add all string value without proper input validation handle and it may fail as a valid SQL statement...debugger will be your good friend here to diagnose further what is the "insert.CommandText" value
pls help me i am stuck in the project and very hard in here.
when i click on the one checkbox in the row which i have set the TrueValue=P in grid view property it store successfuly.but the FalseValue store as null on database. i want to store the 1 instead of the null or 0 so how can i do. it false value i have set in grid view property it didnt work.here is the image of my grid view.
here is my coding after the image of the grid view which store datafrom grid view into datbase.
here is image of the database store value which i want to store the zero instead of the empty or null in cell.
i just want to get the False value of the checkbox should store in database.
thanks.
my code for storing the value of the checkbox in the project.
{
foreach (DataGridViewRow iteam in dtgAttandance.Rows)
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO EmpAttandanceDetail Values('"
+txtAttandID.Text+"','"
+ iteam.Cells[0].Value + "','"
+ iteam.Cells[1].Value + "','"
+ iteam.Cells[2].Value + "','"
+ iteam.Cells[3].Value + "','"
+ iteam.Cells[4].Value + "','"
+ iteam.Cells[5].Value + "','"
+ iteam.Cells[6].Value+ "','"
+ iteam.Cells[7].Value+ "','"
+ iteam.Cells[8].Value+ "')",con);
cmd.ExecuteNonQuery();
con.Close();
}
con.Open();
SqlCommand cmdDetail = new SqlCommand("INSERT INTO EmpAttandance values('" + txtAttandID.Text + "','" + dtAttand.Text + "')", con);
cmdDetail.ExecuteNonQuery();
MessageBox.Show("Attandance Save Successfully");
con.Close();
AttandanceDateVerifier();
}
As a quick fix, you can invert cell 7's value: + !((bool)iteam.Cells[7].Value) + "','" might help, but I urge you to check the Parameterizing the SqlCommand links. It will force you to think about data types and will make your problem easier.
For a few week I've been working on this application. One of the users wishes was to save and display images. So I've created this opportunity for the user to insert screenshots. However, when I first send the images to the database and retrieve them again, they can't be decoded into images anymore. (Error: Parameter is not valid.) So I checked whether is was the code or something else. I found out, that after converting the image into byte[], I could revert and display that without any trouble. So the problem lays somewhere between writing to the database and getting it back again. I had a look in the database, and noticed that every image started with 0x, even if there was no image to upload. I read something about some databases might add a header, so I guess that's what creates the problem. But now I need to know how to get rid of that header. And if I get rid of that reader, can I still just use the GetValue() function, or do I really need to use GetBytes()? The reason I didn't go for GetBytes in the first place, is that I need to assign a length in start, but that changes from image to image.
Can anyone tell me how to delete that header if that comes with it? I checked the values of the first few bytes, I hoped if I dropped the first two, they represent the 0x and the problem would be solved, but that's not how it works apparently. After that, I tried to upload a picture to the db and retrieve it again, I noticed the length went from 566 to 1335. The empty picture however, despite that the db says it has 0x in it, has a byte[] with a length of 0.
The object bsk will be send to a part of the code, which writes that to the database:
String command = "INSERT INTO " + db.getTabelbsk() + " VALUES ('" + bsk.getEmailapplicant() + "','" + bsk.getCreation().ToString("MM-dd-yyyy") + "','" + bsk.getCrmQuoteNumber()
+ "','" + bsk.getProjectStage() + "','" + bsk.getRefArticleId() + "','" + bsk.getClassification() + "','" + bsk.getDescription() + "','" +
bsk.getTrackingnumber() + "','" + bsk.getLastModified().ToString("MM-dd-yyyy") + "','" + bsk.getStatus() + "','" + bit + "','" + bsk.getScr() + "','" +
bsk.getBskMail() + "','" + bsk.getEnd12Mail() + "','" + bsk.getEnd3elecMail() + "','" + bsk.getEnd3swMail() + "','" + bsk.getPrmMail() + "','" +
bsk.getRejectMail() + "','" + bsk.getRejectReason() + "','" + bsk.getCommercialDescription() + "','" + bsk.getTechnicalDescription() + "','" +
bsk.getValue() + "','" + bsk.getEndhours() + "', '" + bsk.getLockedBy() + "', '";
command = addImages(command, bsk.getSrcSs()) + "', '" + addImages(command, bsk.getTechnicalDescriptionSs()) + "');";
sqlcommand(con, command);
private String addImages(String command, byte[] ba)
{ //Adds every byte to the command String
foreach (byte b in ba)
{
command += b;
}
return command;
}
public SqlDataReader sqlcommand(SqlConnection con, String s)
{ //Executes the command
try
{
con.Close();
}
catch { }
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = s;
cmd.Connection = con;
try
{
con.Open();
}
catch
{
}
SqlDataReader reader = cmd.ExecuteReader();
return reader;
}
This part is used to retrieve data from the database:
public Bsk returnBsk(Database db, Bsk bsk, SqlConnection con)
{ //This will retrieve the data from the database
String table = db.getTabelbsk();
int trackingnumber = bsk.getTrackingnumber();
String command = "SELECT * FROM " + table + " WHERE trackingNumber = " + trackingnumber;
SqlDataReader reader = sqlcommand(con, command);
reader.Read(); //Filling the object with data
bsk.setEmailapplicant(reader.GetString(0));
bsk.setCreation(reader.GetDateTime(1));
bsk.setCrmQuoteNumber(reader.GetString(2));
bsk.setProjectStage(reader.GetString(3));
bsk.setRefArticleId(reader.GetString(4));
bsk.setClassification(reader.GetString(5));
bsk.setDescription(reader.GetString(6));
bsk.setLastModified(reader.GetDateTime(8));
bsk.setStatus((Bsk.Status)Enum.Parse(typeof(Bsk.Status), reader.GetString(9)));
if (reader.GetBoolean(10) == false)
{
bsk.setComplexity((Bsk.Complexity.Simple));
}
else if (reader.GetBoolean(10) == true)
{
bsk.setComplexity((Bsk.Complexity.Complex));
}
bsk.setScr(reader.GetString(11));
bsk.setBskMail(reader.GetString(12));
bsk.setEnd12Mail(reader.GetString(13));
bsk.setEnd3elecMail(reader.GetString(14));
bsk.setEnd3swMail(reader.GetString(15));
bsk.setPrmMail(reader.GetString(16));
bsk.setRejectMail(reader.GetString(17));
bsk.setRejectReason(reader.GetString(18));
bsk.setCommercialDescription(reader.GetString(19));
bsk.setTechnicalDescription(reader.GetString(20));
bsk.setValue(reader.GetInt32(21));
bsk.setEndhours(reader.GetInt32(22));
bsk.setLockedBy(reader.GetString(23));
if (!Convert.IsDBNull(reader.GetValue(24)))
{
bsk.setSrcSs((byte[])reader.GetValue(24));
}
if (!Convert.IsDBNull(reader.GetValue(25)))
{
bsk.setTechnicalDescriptionSs((byte[])reader.GetValue(25));
}
reader.Close();
con.Close();
return bsk;
}
Image to byte[]:
Image imageSrc = pb_Src.Image;
byte[] arrSrc;
ImageConverter converterSrc = new ImageConverter();
arrSrc = (byte[])converterSrc.ConvertTo(imageSrc, typeof(byte[]));
bsk.setSrcSs(arrSrc);
byte[] to image:
byte[] arrSrc = bsk.getSrcSs();
MemoryStream ms = new MemoryStream(arrSrc);
pb_Src.Image = Image.FromStream(ms); <-- Error message appears here
PS:
I'm aware that How to display image from database in c# is related. However, this question never got answered.
I have a simple user interface for an inventory database. The operation will be insert into, edit existing, view data grid, etc....There are a total of 4 fields for the inventory. The insert statement I am using works but if one of the entries does not have a value then it shows an error when trying to insert.
" Data type mismatch in criteria expression "
command.CommandText = "insert into Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" + txtPart.Text + "','" + txtSerial.Text + "','" +
txtRO.Text + "','" + txtLocation.Text + "')";
I assume it is because the code needs a value for each field so how do I get around this issue?.
Actually when you trying to use this query you have said the First Parameter is SerialNumber and then PartNumber and when you are passing its reverse.
command.CommandText = "insert into Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" + txtPart.Text + "','" +
txtSerial.Text + "','" +
txtRO.Text + "','" +
txtLocation.Text + "')";
Due to this reason the fields you are entering have different size May be part number is bigger in size instead of SerialNumber or vice versa. So you should change it to
command.CommandText = "insert into Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" + txtSerial.Text + "','" +
txtPart.Text + "','" +
txtRO.Text + "','" +
txtLocation.Text + "')";