If combobox not selected any item enter empty string into Access database - c#

When I enter a data in my Access database, if I do not select any item in the combobox, I get an error of null exception. So how can I make sure that if I did not select any items, empty data is inserted into my database?
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");
if (comboBox10.SelectedItem == null)
{
comboBox10.Text = " ";
}
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10.SelectedItem.ToString() + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Data Inserted Successfully");
con.Close();

You can check if the SelectedItem property is null, then set a temp variable to use in your query string.
string comboBox10Text = comboBox10.SelectedItem == null ? String.Empty : comboBox10.Text;
Then use comboBox10Text in your query string.
Edit:
// Check if comboBox10.SelectedItem is null, set temp variable
string comboBox10Text = comboBox10.SelectedItem == null ? String.Empty : comboBox10.Text;
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
// Update query string to use comboBox10Text instead of accessing SelectedItem
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10Text + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Data Inserted Successfully");
con.Close();

You can have a null check and change the condition
If(comboBox10.SelectedItem != null)
{
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10.SelectedItem.ToString() + "')";
}
else
{
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + "" + "')";
}

Related

How do I make the column type date I want to insert in sql

I want to insert the date format into sql
How can I do this?
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection("Data Source=Server-1;Initial Catalog=Eczane;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO TBL_Musteri (MUSTERI_TC,MUSTERI_AD,MUSTERI_SOYADI,MUSTERI_DOGUM_TARIHI,MUSTERI_CINSIYET,MUSTERI_TELEFON,MUSTERI_ADRES,MUSTERI_IL,MUSTERI_ILCE,MUSTERI_EKLEYEN_ADMIN) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox9.Text + "','" + comboBox1.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception)
{
MessageBox.Show("Erorr!");
}
}
Use Parameters collection on cmd object.
You can specify the type and the conversion will be done for you. Also it prevents your code from being exposed to SQL injection.
SqlCommand cmd = new SqlCommand("INSERT INTO TBL_Musteri (MUSTERI_TC,MUSTERI_AD,MUSTERI_SOYADI,MUSTERI_DOGUM_TARIHI,
MUSTERI_CINSIYET,MUSTERI_TELEFON,MUSTERI_ADRES,MUSTERI_IL,MUSTERI_ILCE,MUSTERI_EKLEYEN_ADMIN)
VALUES (#param1,#param2,#param3,#param4,#param5,
#param6,#param7,#param8,#param9,#param10)", conn);
cmd.Parameters.Add("#param1", SqlDbType.NVarChar);
cmd.Parameters["#param1"] = textBox1.Text;
...
cmd.Parameters.Add("#param4", SqlDbType.Date;
cmd.Parametes["#param4"] = textBox9.Text;
...

Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll

Below is my add button code, every time I click add button give this error
command.ExecuteNonQuery(); can help me with the problem?
Here is my code
private void button4_Click(object sender, EventArgs e) //Add button
{
tbLecturerId.Select();
string strID, strFirstName, strUsername, strPassword, strDepartment, strEmail;
strID = tbLecturerId.Text;
strFirstName = tbLname.Text;
strUsername = Usernametxt.Text;
strPassword = Passwordtxt.Text;
strDepartment = cbDepartment.Text;
strEmail = tbEmail.Text;
connect.Open();
SqlCommand command = new SqlCommand(#"INSERT INTO Lecturer_tbl (LecturerID,LecturertName, Username,Password, Department,Email) VALUES('" + strID + "','" + strFirstName + "','" + strUsername + "', '" + strPassword + "','" + strDepartment + "' ,'" + strEmail + "')", connect);
command.ExecuteNonQuery();
connect.Close();
displayLectureGrid();
clearLecturertbl();
There is a space and comma problem in your statement. Try this
SqlCommand command = new SqlCommand(#"INSERT INTO Lecturer_tbl (LecturerID,LecturertName,Username,Password,Department,Email) VALUES('" + strID + "','" + strFirstName + "','" + strUsername + "','" + strPassword + "','" + strDepartment + "','" + strEmail + "')", connect);

how do i get id of the last inserted row

i want to display booking id of the last inserted row.my insert code is given below. pls anyone can give me code to display the id
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd;
SqlDataReader dr;
con.Open();
cmd = new SqlCommand("insert into [booking] values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "')", con);
cmd.ExecuteNonQuery();
}
}
I would suggest using something like this:
protected void Button1_Click(object sender, EventArgs e)
{
var cs = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using (var con = new SqlConnection(cs))
{
con.Open();
var cmd = new SqlCommand(
"DECLARE #IDReturnTable TABLE( ID INT ); INSERT INTO [booking] OUTPUT INSERTED.NameOfYourIdColumn INTO #IDReturnTable VALUES(#param1, #param2, #param3); SELECT ID FROM #IDReturnTable",
con);
cmd.Parameters.Add("#param1", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("#param2", SqlDbType.VarChar).Value = TextBox2.Text;
cmd.Parameters.Add("#param3", SqlDbType.VarChar).Value = TextBox3.Text;
var returnedId = cmd.ExecuteScalar();
}
}
I didn't use all 11 Text Boxes, just 3 to illustrate the technique.
You will be better off doing this as a stored procedure, and less susceptible to injection.
To achieve it with your current code, add a call to ;SELECT SCOPE_IDENTITY():
cmd = new SqlCommand("insert into [booking] values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "');SELECT SCOPE_IDENTITY()", con);
And execute as scalar:
var id = cmd.ExecuteScalar();
(This assumes you have an identity column on your table)
To do it as a stored procedure:
If you have a finite number of values, you can just create the stored procedure normally, with an #Parameter for each TextBox.Text but with SELECT SCOPE_IDENTITY() at the end.
But it looks like you have a variable number of inputs, so see How to insert a multiple rows in SQL using stored procedures? which outlines an approach using a table paramater and one using a UDF to split a list of values.
Again, you would need to SELECT SCOPE_IDENTITY() at the end of the proc to pick up the identity of the last row.
For a detailed discussion on the ways of selecting the last inserted id see What is the difference between Scope_Identity(), Identity(), ##Identity, and Ident_Current?

How to delete previous table transaction if next table transaction fails

I'm inserting some data to tables one by one. I've two tables adjustment_header and adjustment_grid.
First I'll insert data to adjustment_header table then I'll insert data to adjustment_grid table. If adjustment insertion fails, previously inserted data in adjustment_header table should be delete automatically.
Is there any query for this kind of problem?
SqlCommand sqlcmd1 = new SqlCommand("INSERT INTO adjustment_header values('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"','"+TextBox4.Text+"')",conn);
conn.Open();
sqlcmd1.ExecuteNonQuery();
conn.Close();
//adjustment grid row 1
if (itemno1.SelectedItem.Text != "please select")
{
SqlCommand cmd1 = new SqlCommand("INSERT INTO adjustment_grid values('"+TextBox1.Text+"','" + itemno1.SelectedItem.Text + "','" + adj1.SelectedItem.Text + "','" + store1.SelectedItem.Text + "','" + qty1.Text + "','" + cost1.Text + "')", conn);
conn.Open();
cmd1.ExecuteNonQuery();
conn.Close();
}
//adjustment grid row 2
if (itemno2.SelectedItem.Text != "please select")
{
SqlCommand cmd2 = new SqlCommand("INSERT INTO adjustment_grid values('" + TextBox1.Text + "','" + itemno2.SelectedItem.Text + "','" + adj2.SelectedItem.Text + "','" + store2.SelectedItem.Text + "','" + qty2.Text + "','" + cost2.Text + "')", conn);
conn.Open();
cmd2.ExecuteNonQuery();
conn.Close();
}
//adjustment grid row 3
if (itemno3.SelectedItem.Text != "please select")
{
SqlCommand cmd3 = new SqlCommand("INSERT INTO adjustment_grid values('" + TextBox1.Text + "','" + itemno3.SelectedItem.Text + "','" + adj3.SelectedItem.Text + "','" + store3.SelectedItem.Text + "','" + qty3.Text + "','" + cost3.Text + "')", conn);
conn.Open();
cmd3.ExecuteNonQuery();
conn.Close();
}
In this code first I'm inserting data into adjustment_header table then I'm inserting into adjustment_grid table 3 times, in 3 transactions in adjustment_grid table any of one fails previously inserted data should be delete automatically.
Wrap the entire block in a SqlTransaction, and don't open/close your connection for each statement:
conn.Open();
using(SqlTransaction tran = conn.BeginTransaction("Adjustment"))
{
SqlCommand sqlcmd1 = new SqlCommand("INSERT INTO adjustment_header values('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"','"+TextBox4.Text+"')",conn, tran);
sqlcmd1.ExecuteNonQuery();
//adjustment grid row 1
if (itemno1.SelectedItem.Text != "please select")
{
SqlCommand cmd1 = new SqlCommand("INSERT INTO adjustment_grid values('"+TextBox1.Text+"','" + itemno1.SelectedItem.Text + "','" + adj1.SelectedItem.Text + "','" + store1.SelectedItem.Text + "','" + qty1.Text + "','" + cost1.Text + "')", conn, tran);
cmd1.ExecuteNonQuery();
}
//adjustment grid row 2
if (itemno2.SelectedItem.Text != "please select")
{
SqlCommand cmd2 = new SqlCommand("INSERT INTO adjustment_grid values('" + TextBox1.Text + "','" + itemno2.SelectedItem.Text + "','" + adj2.SelectedItem.Text + "','" + store2.SelectedItem.Text + "','" + qty2.Text + "','" + cost2.Text + "')", conn, tran);
cmd2.ExecuteNonQuery();
}
//adjustment grid row 3
if (itemno3.SelectedItem.Text != "please select")
{
SqlCommand cmd3 = new SqlCommand("INSERT INTO adjustment_grid values('" + TextBox1.Text + "','" + itemno3.SelectedItem.Text + "','" + adj3.SelectedItem.Text + "','" + store3.SelectedItem.Text + "','" + qty3.Text + "','" + cost3.Text + "')", conn, tran);
cmd3.ExecuteNonQuery();
}
tran.Commit();
}
You should also use parameters instead of string concatenation, but that's a separate issue...
I would ALSO not reference your controls directly. Put this type of logic in a separate class in a function that has parameters for the various options. That way you can decouple it from the UI and reuse it later if necessary.

System.Web.UI.WebControls.DataGrid' does not contain a definition for 'Rows'

I got the excel value in gridview and now I need to insert all the values in rows to sql server 2008.
When i try to iterate throught Gridview rows it throws the error in for loop near the dg_AgentSFR.Rows as "DataGrid' does not contain a definition for 'Rows' "
Here is my code:
protected void savedatafromgv()
{
foreach (GridViewRow g1 in ***dg_AgentSFR.Rows)***
{
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = con.CreateCommand();
cmd = new SqlCommand("INSERT INTO TB_TransAgenSeaFreightRate(POL,POD,FORWARDER,FORWARDER REFERENCE,SHIPPING LINE,CONTAINER TYPE,CONTAINER SIZE,VALIDITY FROM,VALIDITY TO,BASIC RATE,PAF,CAF,PSS,TOTAL AMOUNT,REE DAYS,CREDIT DAYS,NIT DEPOSIT,COMPANYID,ISACTIVE) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "','" + g1.Cells[4].Text + "','" + g1.Cells[5].Text + "','" + g1.Cells[6].Text + "','" + g1.Cells[7].Text + "','" + g1.Cells[8].Text + "','" + g1.Cells[9].Text + "','" + g1.Cells[10].Text + "','" + g1.Cells[11].Text + "','" + g1.Cells[12].Text + "','" + g1.Cells[13].Text + "','" + g1.Cells[14].Text + "','" + g1.Cells[15].Text + "','" + g1.Cells[16].Text + "',1,'" + TXTCompanyID.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Response.Write ("Records inserted successfully");
}
Please help me to resolve this.
Thanks in advance.
Datagrid does not contain a definition for rows. Instead of rows, it has items.
use this
foreach (DataGridItem Dr in dg_AgentSFR.items)
DataGrid Class
And also use parameterized query to avoid How does SQLParameter prevent SQL Injection
cmd = new SqlCommand("INSERT INTO TB_TransAgenSeaFreightRate(POL,POD,FORWARDER....) values (#POL,#POD,#FORWARDER)
try this code
if(dg_AgentSFR.Rows.Count>0)
{
foreach (GridViewRow g1 in dg_AgentSFR.Rows)
{
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = con.CreateCommand();
cmd = new SqlCommand("INSERT INTO TB_TransAgenSeaFreightRate(POL,POD,FORWARDER,FORWARDER REFERENCE,SHIPPING LINE,CONTAINER TYPE,CONTAINER SIZE,VALIDITY FROM,VALIDITY TO,BASIC RATE,PAF,CAF,PSS,TOTAL AMOUNT,REE DAYS,CREDIT DAYS,NIT DEPOSIT,COMPANYID,ISACTIVE) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "','" + g1.Cells[4].Text + "','" + g1.Cells[5].Text + "','" + g1.Cells[6].Text + "','" + g1.Cells[7].Text + "','" + g1.Cells[8].Text + "','" + g1.Cells[9].Text + "','" + g1.Cells[10].Text + "','" + g1.Cells[11].Text + "','" + g1.Cells[12].Text + "','" + g1.Cells[13].Text + "','" + g1.Cells[14].Text + "','" + g1.Cells[15].Text + "','" + g1.Cells[16].Text + "',1,'" + TXTCompanyID.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Response.Write ("Records inserted successfully");
}
A datagrid in ASP.NET does indeed not contain a property Rows. The GridView on the other hand, does contain a property Rows. More info:
DataGrid class
GridView class
I suggest you use the GridView, this is kind of the successor of the DataGrid. And another important tip: use SQL parameters and not just a string-query (SQL injection).
Make sure you use GridViewRowEventArgs and NOT GridViewCommandEventArgs
protected void gvSample_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Your code here
}

Categories

Resources