I don't understand where the problem is, I try to fix, to search and I can't find the problem.
Incorrect syntax near ','.
Code:
using System.Data.SqlClient;
SqlConnection ABC = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\kindl\Desktop\WindowsFormsApplication2\WindowsFormsApplication2\bd_formular.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand comm = new SqlCommand();
SqlDataReader dataRead;
private void B1_Click(object sender, EventArgs e)
{
ABC.Open();
comm.CommandText = "insert into dbo.bd_formular(facultate,domeniul,specializare,forma_invatamant,d_inscriere,nume_prenume,cod,localitate,judet,tara,strada,numar,bloc,scara,etaj,apartament,sector,cod_p,data_nasterii,locul_nasterii,judet_n,tara_n,sex,starea_civila,cetatenie,cetatenie_op,etnie,cnp,serie,numar_cnp,eliberat,e_data,studii_preuni,nume_unitate,spec_fili_profil,oras_s,,judet_s,tara_s,forma_de_invatamant,medie_bac,durata_studii,data_absolvirii,tipul_diploma,seria_diploma,numarul_diploma,emis_de_catre,data_emiterii,nr_foi_matricole,introducere_date,semnatura)values('"
+ C1.Text + "','" + T1.Text + "','" + T2.Text + "','" + C2.Text + "','" + DTP1.Value.ToString("MM/dd/yyyy") + "','" + T3.Text + "','" + T4.Text + "','" + T5.Text + "','" + T6.Text + "','" + T7.Text + "','"
+ T8.Text + "','" + T9.Text + "','" + T10.Text + "','" + T11.Text + "','" + T12.Text + "','" + T13.Text + "','" + T14.Text + "','" + T15.Text + "','" + DTP2.Value.ToString("MM/dd/yyyy") + "','" + T16.Text + "','" + T17.Text + "','" + T18.Text + "','" + C3.Text + "','" + C4.Text + "','" + C5.Text + "','" + T19.Text + "','" + T20.Text + "','" + C6.Text + "','" + T21.Text + "','" + T22.Text + "','" + T23.Text + "','" + T24.Text + "','" + DTP3.Value.ToString("MM/dd/yyyy") + "','" + C7.Text + "','" + T25.Text
+ "','" + T26.Text + "','" + T27.Text + "','" + T28.Text + "','" + T29.Text + "','" + C8.Text + "','" + T30.Text + "','" + C9.Text + "','" + DTP4.Value.ToString("MM/dd/yyyy") + "','" + C10.Text + "','" + T31.Text + "','" + T32.Text + "','" + T33.Text + "','" + DTP5.Value.ToString("MM/dd/yyyy") + "','" + T34.Text + "','" + T35.Text + "','" + T36.Text + "')";
comm.ExecuteNonQuery();
ABC.Close();
MessageBox.Show("Adaugat cu succes!");
}
You have two commas successively. Remove the same.
Suggestion: Please use parameterized queries.
As already pointed out the Exception is caused by a double , in your statement. Really you need to use Sql Parameters. Also use the using statement, and do not share connection instances (again, see the link).
// store this in the app.config instead of hard coding
const string SqlConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\kindl\Desktop\WindowsFormsApplication2\WindowsFormsApplication2\bd_formular.mdf;Integrated Security=True;Connect Timeout=30";
private void B1_Click(object sender, EventArgs e)
{
const string sqlText = "INSERT INTO dbo.bd_formular(facultate,domeniul,specializare,forma_invatamant,d_inscriere,nume_prenume,cod,localitate,judet,tara,strada,numar,bloc,scara,etaj,apartament,sector,cod_p,data_nasterii,locul_nasterii,judet_n,tara_n,sex,starea_civila,cetatenie,cetatenie_op,etnie,cnp,serie,numar_cnp,eliberat,e_data,studii_preuni,nume_unitate,spec_fili_profil,oras_s,judet_s,tara_s,forma_de_invatamant,medie_bac,durata_studii,data_absolvirii,tipul_diploma,seria_diploma,numarul_diploma,emis_de_catre,data_emiterii,nr_foi_matricole,introducere_date,semnatura) VALUES (#facultate,#domeniul,#specializare,#forma_invatamant,#d_inscriere,#nume_prenume,#cod,#localitate,#judet,#tara,#strada,#numar,#bloc,#scara,#etaj,#apartament,#sector,#cod_p,#data_nasterii,#locul_nasterii,#judet_n,#tara_n,#sex,#starea_civila,#cetatenie,#cetatenie_op,#etnie,#cnp,#serie,#numar_cnp,#eliberat,#e_data,#studii_preuni,#nume_unitate,#spec_fili_profil,#oras_s,#judet_s,#tara_s,#forma_de_invatamant,#medie_bac,#durata_studii,#data_absolvirii,#tipul_diploma,#seria_diploma,#numarul_diploma,#emis_de_catre,#data_emiterii,#nr_foi_matricole,#introducere_date,#semnatura)";
// use using statements to ensure connections are closed and resources are freed
using(var con = new SqlConnection(SqlConnectionString))
using(var comm = new SqlCommand(sqlText, con))
{
comm.Parameters.Add(new SqlParameter("#facultate", SqlDbType.VarChar){Value = C1.Text});
comm.Parameters.Add(new SqlParameter("#domeniul", SqlDbType.VarChar){Value = T1.Text});
// etc, fill this in with the remaining parameters
con.Open();
comm.ExecuteNonQuery();
// not really a great place for this, I recommend splitting the ADO.NET code from the UI code
MessageBox.Show("Adaugat cu succes!");
}
}
Finally understand what Exceptions are and how to read them.
this is right query try it
using System.Data.SqlClient;
SqlConnection ABC = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\kindl\Desktop\WindowsFormsApplication2\WindowsFormsApplication2\bd_formular.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand comm = new SqlCommand();
SqlDataReader dataRead;
private void B1_Click(object sender, EventArgs e)
{
ABC.Open();
comm.CommandText = "insert into dbo.bd_formular(facultate,domeniul,specializare,forma_invatamant,d_inscriere,nume_prenume,cod,localitate,judet,tara,strada,numar,bloc,scara,etaj,apartament,sector,cod_p,data_nasterii,locul_nasterii,judet_n,tara_n,sex,starea_civila,cetatenie,cetatenie_op,etnie,cnp,serie,numar_cnp,eliberat,e_data,studii_preuni,nume_unitate,spec_fili_profil,oras_s,judet_s,tara_s,forma_de_invatamant,medie_bac,durata_studii,data_absolvirii,tipul_diploma,seria_diploma,numarul_diploma,emis_de_catre,data_emiterii,nr_foi_matricole,introducere_date,semnatura)values('"
+ C1.Text + "','" + T1.Text + "','" + T2.Text + "','" + C2.Text + "','" + DTP1.Value.ToString("MM/dd/yyyy") + "','" + T3.Text + "','" + T4.Text + "','" + T5.Text + "','" + T6.Text + "','" + T7.Text + "','"
+ T8.Text + "','" + T9.Text + "','" + T10.Text + "','" + T11.Text + "','" + T12.Text + "','" + T13.Text + "','" + T14.Text + "','" + T15.Text + "','" + DTP2.Value.ToString("MM/dd/yyyy") + "','" + T16.Text + "','" + T17.Text + "','" + T18.Text + "','" + C3.Text + "','" + C4.Text + "','" + C5.Text + "','" + T19.Text + "','" + T20.Text + "','" + C6.Text + "','" + T21.Text + "','" + T22.Text + "','" + T23.Text + "','" + T24.Text + "','" + DTP3.Value.ToString("MM/dd/yyyy") + "','" + C7.Text + "','" + T25.Text
+ "','" + T26.Text + "','" + T27.Text + "','" + T28.Text + "','" + T29.Text + "','" + C8.Text + "','" + T30.Text + "','" + C9.Text + "','" + DTP4.Value.ToString("MM/dd/yyyy") + "','" + C10.Text + "','" + T31.Text + "','" + T32.Text + "','" + T33.Text + "','" + DTP5.Value.ToString("MM/dd/yyyy") + "','" + T34.Text + "','" + T35.Text + "','" + T36.Text + "')";
comm.ExecuteNonQuery();
ABC.Close();
MessageBox.Show("Adaugat cu succes!");
}
Also try to use parameterized queries.
Related
I have one form having revise button is to update existing data in database. insert query executed successfully but data is not inserted
This is the code I use:
private void btnupdate_Click(object sender, EventArgs e)
{
try
{
int row = dataGridView1.RowCount;
for (int i = 0; i < row - 1; i++)
{
String str = "INSERT INTO JDS_Data(E_JDS_ID,E_JDS_Revision,DesignSpec,Engine_Type,Record_date,CPH_Designer,Exp_Del_Week,Rev_Description,Name_of_mock_up,EPC_Drawing,Turbocharger_no_Type,Engine_Specific_Requirement,Description_of_Job,SF_No,Standard,Task_No,SF_revision,Part_family,Action_code,Remark,Modified_Date,UserName) values('" + txtjobno.Text + "','" + comboBox1.SelectedItem + "','" + txtds.Text + "','" + txtenginetype.Text + "','" + dateTimePicker1.Text + "','" + txtcphdesigner.Text + "','" + txtexpweek.Text + "','" + txtrevdescription.Text + "','" + txtmockup.Text + "','" + txtepcdwg.Text + "','" + txtturbono.Text + "','" + txtenginereq.Text + "','" + txtdespjob.Text + "','" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[2].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[3].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[4].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[5].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[6].Value.ToString() + "','" + DateTime.Today.ToString("dd-MM-yyyy") + "','" + mdlconnection.user_name + "')";
int dd = mdlconnection.excuteQuery(str);
}
MessageBox.Show("Data Revised Successfully..!!!");
}
catch (Exception e2)
{
MessageBox.Show("" + e2.Message);
}
int rw = dataGridView2.RowCount;
for (int i = 0; i < rw - 1; i++)
{
String str = "INSERT INTO JDS_files(E_JDS_ID,SF_NO,PATH,Filename) values('" + txtjobno.Text + "','" + dataGridView2.Rows[i].Cells[0].Value.ToString() + "','" + dataGridView2.Rows[i].Cells[1].Value.ToString() + "','" + dataGridView2.Rows[i].Cells[2].Value.ToString() + "')";
int dd = mdlconnection.excuteQuery(str);
}
btnupdate.Enabled = false;
}
How do I properly use an OleDbCommand to insert into two different tables? Here is what I have tried so far:
GradeConn.Open();
oledDbCmd.Connection = GradeConn;
oledDbCmd.CommandText = "insert into StudentInfo (IdNumber, LastName,FirstName,MiddleName,YearSection,MidtermGrade) values ('" +
txbIdNumber.Text + "','" +
txbLastName.Text + "','" +
txbFirstName.Text + "','" +
txbMiddleName.Text + "','" +
txbYearSection.Text + "','" +
dmg + "')"; "insert into MidTerm (IdNumber,StudentName, QuizzesSeatworks,ClassParticipation,Attendance,Assignments, LaboratoryExercises, CaseStudy,Behavior,ClassStanding,MidtermExam,MidtermGrade ) values('" +
txbIdNumber.Text + "', '" +
txbStudentName.Text + "','" +
mquiz + "','" +
mcp + "','" +
matt + "','" +
mass + "','" +
mlab + "','" +
mcstu + "','" +
mbeh + "','" +
mstanding + "','" +
mte + "','" +
dmg + "')";
int temp = oledDbCmd.ExecuteNonQuery();
if (temp > 0)
{
txbIdNumber.Text = null;
txbLastName = null;
txbFirstName.Text = null;
txbMiddleName.Text = null;
txbYearSection.Text = null;
txbStudentName.Text = null;
MessageBox.Show("Records Successfully Added");
}
else
{
MessageBox.Show("Records Fail to Added");
}
Change to this and try. You are missing ; (semicolon in the queries)
oledDbCmd.CommandText = "insert into StudentInfo (IdNumber, LastName,FirstName,MiddleName,YearSection,MidtermGrade) values ('" +
txbIdNumber.Text + "','" +
txbLastName.Text + "','" +
txbFirstName.Text + "','" +
txbMiddleName.Text + "','" +
txbYearSection.Text + "','" +
dmg + "'); INSERT into MidTerm (IdNumber,StudentName, QuizzesSeatworks,ClassParticipation,Attendance,Assignments, LaboratoryExercises, CaseStudy,Behavior,ClassStanding,MidtermExam,MidtermGrade ) values('" +
txbIdNumber.Text + "', '" +
txbStudentName.Text + "','" +
mquiz + "','" +
mcp + "','" +
matt + "','" +
mass + "','" +
mlab + "','" +
mcstu + "','" +
mbeh + "','" +
mstanding + "','" +
mte + "','" +
dmg + "')";
I have a problem when it comes to inserting table
I have tables Personaldata and Spouse
Insert statement in table Spouse is functioning. however, I cant insert in tables Personaldata.
pls help me.
Here's my code:
private void button2_Click(object sender, EventArgs e)
{
personalConn.Open();
oleDbCmd.Connection = personalConn;
oleDbCmd.CommandText = "insert into Personaldata(Bloclno,Lotno,Numberofoccupants,Firstname,Familyname,Dateofbirth,Age,Bloodtype,Placeofbirth,Religion) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + this.textBox4.Text + "','" + this.textBox5.Text + "','" + this.textBox6.Text + "','" + this.textBox7.Text + "','" + this.textBox8.Text + "','" + this.textBox9.Text + "','" + this.textBox10.Text + "');";
oleDbCmd.CommandText = "insert into Spouse(Firstname,Familyname,Dateofbirth,Age,Bloodtype,Placeofbirth,Religion,Startofoccupancy,Contactnumber,NumberofChildren,Numberofdogs, Vaccinatedwithantirabies) values ('" + this.textBox11.Text + "','" + this.textBox12.Text + "','" + this.textBox21.Text + "','" + this.textBox13.Text + "','" + this.textBox14.Text + "','" + this.textBox15.Text + "','" + this.textBox16.Text + "','" + this.textBox17.Text + "','" + this.textBox18.Text + "','" + this.textBox22.Text + "','" + this.textBox25.Text + "','" + this.textBox19.Text + "');";
int temp = oleDbCmd.ExecuteNonQuery();
You can do this way ...
Set CommandText, then execute it, then set another CommandText, and then execute again!
personalConn.Open();
oleDbCmd.Connection = personalConn;
int temp;
oleDbCmd.CommandText = "insert into Personaldata(Bloclno,Lotno,Numberofoccupants,Firstname,Familyname,Dateofbirth,Age,Bloodtype,Placeofbirth,Religion) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + this.textBox4.Text + "','" + this.textBox5.Text + "','" + this.textBox6.Text + "','" + this.textBox7.Text + "','" + this.textBox8.Text + "','" + this.textBox9.Text + "','" + this.textBox10.Text + "');";
temp = oleDbCmd.ExecuteNonQuery();
oleDbCmd.CommandText = "insert into Spouse(Firstname,Familyname,Dateofbirth,Age,Bloodtype,Placeofbirth,Religion,Startofoccupancy,Contactnumber,NumberofChildren,Numberofdogs, Vaccinatedwithantirabies) values ('" + this.textBox11.Text + "','" + this.textBox12.Text + "','" + this.textBox21.Text + "','" + this.textBox13.Text + "','" + this.textBox14.Text + "','" + this.textBox15.Text + "','" + this.textBox16.Text + "','" + this.textBox17.Text + "','" + this.textBox18.Text + "','" + this.textBox22.Text + "','" + this.textBox25.Text + "','" + this.textBox19.Text + "');";
temp = oleDbCmd.ExecuteNonQuery();
string cT = "insert into Personaldata(Bloclno,Lotno,Numberofoccupants,Firstname,Familyname,Dateofbirth,Age,Bloodtype,Placeofbirth,Religion) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + this.textBox4.Text + "','" + this.textBox5.Text + "','" + this.textBox6.Text + "','" + this.textBox7.Text + "','" + this.textBox8.Text + "','" + this.textBox9.Text + "','" + this.textBox10.Text + "');"+
"insert into Spouse(Firstname,Familyname,Dateofbirth,Age,Bloodtype,Placeofbirth,Religion,Startofoccupancy,Contactnumber,NumberofChildren,Numberofdogs, Vaccinatedwithantirabies) values ('" + this.textBox11.Text + "','" + this.textBox12.Text + "','" + this.textBox21.Text + "','" + this.textBox13.Text + "','" + this.textBox14.Text + "','" + this.textBox15.Text + "','" + this.textBox16.Text + "','" + this.textBox17.Text + "','" + this.textBox18.Text + "','" + this.textBox22.Text + "','" + this.textBox25.Text + "','" + this.textBox19.Text + "');";
oleDBCmd.CommandText = cT;
private void button2_Click(object sender, EventArgs e)
{
// try
// {
DateTime admission = Convert.ToDateTime(dtpadmission.Value);
DateTime expiry = Convert.ToDateTime(dtpexpirydate.Value);
DateTime release = Convert.ToDateTime(dtpreleasedate.Value);
DateTime amount = Convert.ToDateTime(dtpreceiptamount.Value);
DateTime warrant = Convert.ToDateTime(dtpwarrantdate.Value);
//dLayer.insertadmitcivilprison(admission.ToString(), txtpmsno.Text.ToString(), txtname.Text.ToString(), txtfname.Text.ToString(), cmbgender.SelectedItem.ToString(), txtoccupation.Text, txtvillage.Text, txtdistrict.Text, txtheight.Text, txtphesiogamy.Text, txtage.Text, cmbresidence.SelectedItem.ToString(), txtcaste.Text, txteducation.Text, txtpolicestation.Text, txtcolor.Text, txtidentification.Text, Txtwhichprison.Text, txtwhytransfered.Text, txtsrnoformerprison.Text, txtnamedetainingcreditor.Text, txtamountofclaim.Text, txtsentenceauthority.Text, txtcauseofdetention.Text, txtwarrantno.Text, warrant.ToString(), expiry.ToString(), release.ToString(), txtweightondischarge.Text, txtweightonadmission.Text, txtrealeaseauthority.Text, txtdurationimprisonment.Text, txtdailydietmonety.Text, txtamountreceived.Text, amount.ToString(), txtprivateproperty.Text, txtbalanceleft.Text, txtbalancedisposedoff.Text);
//MessageBox.Show("Data inserted Successfully");
SqlHelper.ExecuteNonQuery(dLayer.con, CommandType.Text, "insert into pcms.tbl_prisoner_detail (date_of_admission,pmsno,pname,pfname,sex,last_occupation,address,district,height,phesiogamy,age,residence,caste,education_qualification,police_station,color,identification_mark,previous_prison,transfer_reason,registration_no_pre_prison,reason_for_detention,amount_of_claim,sentencing_authority,reason_for_detention,warrant_no,date_of_warrant,expiry_date_imprisonment,date_of_release,weight_on_discharge,weight_on_admission,authority_of_discharge,imprisionment_duration,daily_diet_allowance_granted,amount_received,date_of_recieve,property_recieved,balance_left,balance_disposed_off) values('" + admission.ToString() + "','" + txtpmsno.Text + "','" + txtname.Text + "','" + txtfname.Text + "','" + cmbgender.SelectedItem.ToString() + "','" + txtoccupation.Text + "','" + txtvillage.Text + "','" + txtdistrict.Text + "','" + txtheight.Text + "','" + txtphesiogamy.Text + "','" + txtage.Text + "','" + cmbresidence.SelectedItem.ToString() + "','" + txtcaste.Text + "','" + txteducation.Text + "','" + txtpolicestation.Text + "','" + txtcolor.Text + "','" + txtidentification.Text + "','" + Txtwhichprison.Text + "','" + txtwhytransfered.Text + "','" + txtsrnoformerprison.Text + "','" + txtnamedetainingcreditor.Text + "','" + txtamountofclaim.Text + "','" + txtsentenceauthority.Text + "','" + txtcauseofdetention.Text + "','" + txtwarrantno.Text + "','" + warrant.ToString() + "','" + expiry.ToString() + "','" + release.ToString() + "','" + txtweightondischarge.Text + "','" + txtweightonadmission.Text + "','" + txtrealeaseauthority.Text + "','" + txtdurationimprisonment.Text + "','" + txtdailydietmonety.Text + "','" + txtamountreceived.Text + "','" + amount.ToString() + "','" + txtprivateproperty.Text + "','" + txtbalanceleft.Text + "','" + txtbalancedisposedoff.Text + "')");
}
Code on data layer:
public void insertadmitcivilprison(string dateofadmission,string pmsno, string prisonername, string prisonerfathername, string gender, string occupation, string village, string district, string height, string phesiogamy, string age, string residence, string caste, string education, string police_station, string color, string identification_mark, string from_which_prison, string why_trasfered, string PMS_in_former_prison, string detaining_creditor, string amount_of_claim, string sentencing_authority, string cause_of_detention, string warrant_no, string warrant_date, string expiry_date_imprisonment, string release_date, string weight_on_discharge, string weight_on_admission, string authority_for_release, string duration_imprisonment, string diet_money, string amount_received, string date_receipt_amount, string private_property, string balance_left, string balance_disposedoff)
{
//CallingSystem.SqlHelper.ExecuteNonQuery(con, CommandType.Text, "insert into pcms.tbl_prisoner_detail(pmsno,pname,pfname,pms_no,finger_type,user_status,userid,bal_amount,canteen_bal_amount,reg_date) values('" + pmsno + "','" + prisonername + "','" + prisonerfathername + "','" + pms_no + "','" + finger_type + "','" + user_status + "','" + userid + "','" + bal_amount + "','" + canteen_bal_amount + "','" + reg_date + "')");
CallingSystem.SqlHelper.ExecuteNonQuery(con, CommandType.Text, "insert into pcms.tbl_prisoner_detail (date_of_admission,pmsno,pname,pfname,sex,last_occupation,address,district,height,phesiogamy,age,residence,caste,education_qualification,police_station,color,identification_mark,previous_prison,transfer_reason,registration_no_pre_prison,reason_for_detention,amount_of_claim,sentencing_authority,reason_for_detention,warrant_no,date_of_warrant,expiry_date_imprisonment,date_of_release,weight_on_discharge,weight_on_admission,authority_of_discharge,imprisionment_duration,daily_diet_allowance_granted,amount_received,date_of_recieve,property_recieved,balance_left,balance_disposed_off) values('" + dateofadmission + "','" + pmsno + "','" + prisonername + "','" + prisonerfathername + "','" + gender + "','" + occupation + "','" + village + "','" + district + "','" + height + "','" + phesiogamy + "','" + age + "','" + residence + "','" + caste + "','" + education + "','" + police_station + "','" + color + "','" + identification_mark + "','" + from_which_prison + "','" + why_trasfered + "','" + PMS_in_former_prison + "','" + detaining_creditor + "','" + amount_of_claim + "','" + sentencing_authority + "','" + cause_of_detention + "','" + warrant_no + "','" + warrant_date + "','" + expiry_date_imprisonment + "','" + release_date + "','" + weight_on_discharge + "','" + weight_on_admission + "','" + authority_for_release + "','" + duration_imprisonment + "','" + diet_money + "','" + amount_received + "','" + date_receipt_amount + "','" + private_property + "','" + balance_left + "','" + balance_disposedoff + "')");
}
One or some of that .Value s coming null. You can check them with if conditions. I also recommend you to use parameters instead of giving values directly to sql command. You can find some good tips here: Null parameter checking in C#
dtpadmission.Value ,dtpexpirydate.Value , etc.. In those statement, if it is dtpadmission,dtpexpirydate or any of dates are null ,then cannot read the value from it.It returns object null reference.So better to check those properties are null or not and then set it to the statement.You can do it like as follows.
DateTime admission = Convert.ToDateTime(dtpadmission != null ? dtpadmission.Value.ToString() : null ); // Instead of setting null value you can set the efault value here
OR
in this dLayer.con just check the dLayer object is null or not.
And also if the ToString() methods which you use in like amount.ToString() if they are (amount,etc..) null then occurs the same.
I have written a relatively big insert statement, and some of the fields are null.
I cannot convert from db null to other types and I don't really want to check Convert.IsDBNull for every single item
What should I do?
System.Data.OleDb.OleDbCommand iCommand = new System.Data.OleDb.OleDbCommand("Insert into ProductCode values('" +
greader["CODE"].ToString() +
"','" + Convert.ToChar(greader["DISC_CODE01"]) +
"','" + Convert.ToChar(greader["DISC_CODE02"]) +
"','" + Convert.ToChar(greader["DISC_CODE03"]) +
"','" + Convert.ToChar(greader["DISC_CODE04"]) +
"','" + Convert.ToChar(greader["DISC_CODE05"]) +
"','" + Convert.ToChar(greader["DISC_CODE06"]) +
"','" + Convert.ToChar(greader["DISC_CODE07"]) +
"','" + Convert.ToChar(greader["DISC_CODE08"]) +
"','" + Convert.ToChar(greader["DISC_CODE09"]) +
"','" + Convert.ToChar(greader["DISC_CODE10"]) +
"','" + Convert.ToChar(greader["DISC_CODE11"]) +
"','" + Convert.ToChar(greader["DISC_CODE12"]) +
"','" + Convert.ToChar(greader["DISC_CODE13"]) +
"','" + Convert.ToChar(greader["DISC_CODE14"]) +
"','" + Convert.ToChar(greader["DISC_CODE15"]) +
"','" + Convert.ToChar(greader["DISC_CODE16"]) +
"','" + Convert.ToChar(greader["DISC_CODE17"]) +
"','" + Convert.ToChar(greader["DISC_CODE18"]) +
"','" + Convert.ToChar(greader["DISC_CODE19"]) +
"','" + Convert.ToChar(greader["DISC_CODE20"]) +
"','" + Convert.ToChar(greader["DISC_CODE21"]) +
"','" + Convert.ToChar(greader["DISC_CODE22"]) +
"','" + Convert.ToChar(greader["DISC_CODE23"]) +
"','" + Convert.ToChar(greader["DISC_CODE24"]) +
"','" + Convert.ToChar(greader["DISC_CODE25"]) +
"','" + Convert.ToChar(greader["DISC_CODE26"]) +
"','" + Convert.ToDouble(greader["DISC_PCT01"]) +
"','" + Convert.ToDouble(greader["DISC_PCT02"]) +
"','" + Convert.ToDouble(greader["DISC_PCT03"]) +
"','" + Convert.ToDouble(greader["DISC_PCT04"]) +
"','" + Convert.ToDouble(greader["DISC_PCT05"]) +
"','" + Convert.ToDouble(greader["DISC_PCT06"]) +
"','" + Convert.ToDouble(greader["DISC_PCT07"]) +
"','" + Convert.ToDouble(greader["DISC_PCT08"]) +
"','" + Convert.ToDouble(greader["DISC_PCT09"]) +
"','" + Convert.ToDouble(greader["DISC_PCT10"]) +
"','" + Convert.ToDouble(greader["DISC_PCT11"]) +
"','" + Convert.ToDouble(greader["DISC_PCT12"]) +
"','" + Convert.ToDouble(greader["DISC_PCT13"]) +
"','" + Convert.ToDouble(greader["DISC_PCT14"]) +
"','" + Convert.ToDouble(greader["DISC_PCT15"]) +
"','" + Convert.ToDouble(greader["DISC_PCT16"]) +
"','" + Convert.ToDouble(greader["DISC_PCT17"]) +
"','" + Convert.ToDouble(greader["DISC_PCT18"]) +
"','" + Convert.ToDouble(greader["DISC_PCT19"]) +
"','" + Convert.ToDouble(greader["DISC_PCT20"]) +
"','" + Convert.ToDouble(greader["DISC_PCT21"]) +
"','" + Convert.ToDouble(greader["DISC_PCT22"]) +
"','" + Convert.ToDouble(greader["DISC_PCT23"]) +
"','" + Convert.ToDouble(greader["DISC_PCT24"]) +
"','" + Convert.ToDouble(greader["DISC_PCT25"]) +
"','" + Convert.ToDouble(greader["DISC_PCT26"]) +
"')", iConnect);
Without analysing why you're using the above method, I'd simply write my own method to do this. Simply write your own Convert.ToChar and Convert.ToDouble, something like this:
public class MyConvert
{
public static char ToChar(object value, char defaultValue)
{
return Convert.IsDBNull(value) ? defaultValue : Convert.ToChar(value);
}
}
So rather than having a Convert.ToChar(greader["DISC_CODE01"]) you would use MyConvert.ToChar(greader["DISC_CODE01"], ''). Do the same for double as well.
Dictionary<string, object> greaderDic = new Dictionary<string,object>();
foreach(var item in greader.Items/*or whatever you have to enumerate your greader*/)
{
greaderDic.Add(item.Name, GetValue(item.Name, item.Value));// hope you have something like Name or Value properties
}
object GetValue(string name, objetc value)
{
if (name.StartsWith("DISC_CODE"))
return value == null? "NULL" : Convert.ToChar(value)
if (name.StartsWith("DISC_PCT"))
return value == null? "NULL" : Convert.ToDouble(value);
throw new Exception("Mapping not found for " + item.Name);
}
Additionally replace in old code all greader tokens by greaderDic