whats failed due to data type mismatch in criteria expression c#? - windows

am trying to develop a c# standalone application and my insert code has no error but when i click it will insert to first table or crtPro perfectly but it didn't add to the second table , can anyone give me some hint...???
here is my code for insert code...
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Documents and Settings\abel\My Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String Address = txtAddress.Text.ToString();
//String Wereda = txtWereda.Text.ToString();
//String Kebele = txtKebele.Text.ToString();
//String House_No = txtHouse.Text.ToString();
//String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
//String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String Status = ToString();
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "INSERT INTO crtPro(Name,Address,Email,Tel,Item,Dep,Status,Remark)VALUES('" + Name + "','" + Address + "','" + Email + "','" + Tel + "','" + Item + "','" + Dep + "','" + Remark + "')";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
conn.Close();
conn.Open();
String my_querry1 = "SELECT LAST(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
//txtStatus.Text = var;
String PID = ToString();
String my_querry2 = "INSERT INTO crtItemLicense(PID,Type,Brand,License_No,Date_issued)VALUES('" +PID + "','" + Type + "','" + Brand + "','" + License_No + "','" + Date_issued + "')";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
}

There are a couple of calls like:
String PID = ToString();
That will try to get a string representation of 'this', which is your form. That is probably not what you want to be inserting into the database. You probably meant
String PID = var.ToString();
If that isn't it, then try putting more tracewrites (or using a debugger) to narrow the problem down to find which one of your sql statements is causing the problem.
Also once you have it working, try entering this in the name field of your form:
Robert"); DROP TABLE crtPro;--
and then do some googling about SQL injection (apologies to XKCD).

Related

Output SQL Table to existing Excel file/ new worksheet in SSIS / C# in script task

Good day,
I had a request to create a SSIS package that would output an SQL table to an Excel file. I had no problem creating this. However, the client came back asking that they wanted to be able to output the SQL table content to an existing Excel file in a new worksheet. If the worksheet does not exists in my following script, it is being created. However, it just goes back in the loop and fail because now it exists.
Here is my code:
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["$Package::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["$Package::FolderPath"].Value.ToString();
string TableName = Dts.Variables["$Package::SQLTableName"].Value.ToString();
string SchemaName = Dts.Variables["$Package::SQLTableSchema"].Value.ToString();
string SheetName = Dts.Variables["$Package::SheetName"].Value.ToString();
string lastChar = FolderPath.Substring(FolderPath.Length - 1);
string currentTab;
DataTable ExcelFileTabs;
//Validate format of FolderPath
if (lastChar != "\\")
{
FolderPath = FolderPath + "\\";
}
string FullExcelFilePath = FolderPath + ExcelFileName + ".xlsx";
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FullExcelFilePath + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString = "SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
// Verify if file exists
if (File.Exists(FullExcelFilePath))
{
//Verify if the sheet exists
foreach (DataTable table in ds.Tables)
{
ExcelFileTabs = Excel_OLE_Con.GetSchema("Tables");
foreach (DataRow excelTable in ExcelFileTabs.Rows)
{
currentTab = excelTable["TABLE_NAME"].ToString();
if (currentTab == SheetName)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + "_" + datetime + ".log"))
{
sw.WriteLine("The sheet " + SheetName + " that your are trying to create in " + FullExcelFilePath + " already exists.");
sw.WriteLine("Please enter another sheet name or delete the Excel file and try again.");
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Failure;
}
else
{
// Create the worksheet in the existing Excel file
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
}
}
else
{
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
}
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
ExcelFileTabs = Excel_OLE_Con.GetSchema("Tables");
foreach (DataRow excelTable in ExcelFileTabs.Rows)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + "_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
Can somebody please help me with this ? I am pretty new to C#, and English is not my primary language. Please let me know if this is not clear enough.
Thanks in advance for you time :-)
Mylene
You know when you are trying to find the solution way to fare when it is just in front of you ?
My code, before wanting to catch the error if the user was trying to add a worksheet that already exists, already was trowing an exception in those cases...
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["$Package::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["$Package::FolderPath"].Value.ToString();
string TableName = Dts.Variables["$Package::SQLTableName"].Value.ToString();
string SchemaName = Dts.Variables["$Package::SQLTableSchema"].Value.ToString();
string SheetName = Dts.Variables["$Package::SheetName"].Value.ToString();
ExcelFileName = ExcelFileName + "_" + datetime;
string lastChar = FolderPath.Substring(FolderPath.Length - 1);
//Validate format of FolderPath
if (lastChar != "\\")
{
FolderPath = FolderPath + "\\";
}
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + ExcelFileName
+ ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString = "SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
}
}
Error log :
System.Data.OleDb.OleDbException (0x80040E14): Table 'Test9' already exists.
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at ST_a21007570143466693913591932c30b7.ScriptMain.Main()
Problem resolved.

xxxxxx is not a valid path. Make sure that the path name is

I have windows application that can access files from setting.ini file I modified it and get access to them from my code. but still getting this error like 'C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
here is my setting.ini file code :
[UserDetail]
UserID=xxxxxxx
PassWord=xxxxxxxx
[Connection]
contact=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls
DebitISE=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE 1.xls
DebitLKP=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls
[FilePath]
DebitISEClient=C:
[FileName]
DebitISEClient=Contact_06-07-2015.txt
and here my code for accessing this files from ini file :
private void button1_Click(object sender, EventArgs e)
{
string filepath = txtpayoutfile.Text;
string message = "";
string mobileno = "";
string name = "";
DataSet dsmaster = new DataSet();
string filepathc = ini.IniReadValue("Connection", "contact");
if (filepath == "")
{
MessageBox.Show("Import Contact File");
this.Show();
}
if (Path.GetExtension(filepath) == ".xls")
{
oledbConn1 = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepathc + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(filepath) == ".xlsx")
{
oledbConn1 = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepathc + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
oledbConn1.Open(); ////exception occurs here
if (Path.GetExtension(filepath) == ".xls")
{
oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(filepath) == ".xlsx")
{
oledbConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
OleDbCommand cmdoledb = new OleDbCommand("Select * from [Sheet1$3:3000]", oledbConn);
OleDbDataAdapter daoledb = new OleDbDataAdapter(cmdoledb);
DataTable dt = new DataTable();
daoledb.Fill(dt);
}

my code gets this error:One or more errors occurred during processing of command

I have problem with running this:
i captured picture from my win
OleDbConnection con = new OleDbConnection();
DataTable dt = new DataTable();
con.ConnectionString = "Provider=MSDAORA;Data Source=DATA;Password=ss8_pakhsh;User ID=SHIFTS_N";
con.Open();
string sqlcommand = "INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID) " +
"VALUES(SEQ_MAX_GROUP_ID_NO.NEXTVAL,#groupName,SELECT
DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE
DEPARTMENT_NAME=#depName)";
OleDbCommand command = new OleDbCommand(sqlcommand, con);
command.Parameters.AddWithValue("#groupName", textBox1.Text);
command.Parameters.AddWithValue("#depName", comboBox1.SelectedItem);
OleDbDataAdapter oda = new OleDbDataAdapter(command);
oda.Fill(dt);
dataGridView2.DataSource = dt;
con.Close();
Change the sqlcommand string as shown below,
string sqlcommand = "INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID) " +
"VALUES(SEQ_MAX_GROUP_ID_NO.NEXTVAL,#groupName,SELECT "+
"DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE "+
"DEPARTMENT_NAME=#depName)";
This should solve the issue.
Observation: It is not a good practice to directly set the textBox1.Text value in parameter.

List domain users with wmi

I want to list all users of a Windows domain with WMI in C#.
Can someone help me?
Here is my code:
try
{
ConnectionOptions connection = new ConnectionOptions();
connection.Username = user;
connection.Authority = "ntlmdomain:" + domain;
connection.Password = pwd;
SelectQuery query = new SelectQuery("SELECT * FROM Win32_UserAccount");
ManagementScope scope = new ManagementScope(#"\\FullComputerName\\root\\CIMV2", connection);
scope.Connect();
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("Account Type: " + queryObj["AccountType"]);
Console.WriteLine("Caption: " + queryObj["Caption"]);
Console.WriteLine("Description: " + queryObj["Description"]);
Console.WriteLine("Disabled: " + queryObj["Disabled"]);
Console.WriteLine("Domain: " + queryObj["Domain"]);
Console.WriteLine("Full Name: " + queryObj["FullName"]);
Console.WriteLine("Local Account: " + queryObj["LocalAccount"]);
Console.WriteLine("Lockout: " + queryObj["Lockout"]);
Console.WriteLine("Name: " + queryObj["Name"].ToString());
Console.WriteLine("Password Changeable: " + queryObj["PasswordChangeable"]);
Console.WriteLine("Password Expires: " + queryObj["PasswordExpires"]);
Console.WriteLine("Password Required: " + queryObj["PasswordRequired"]);
Console.WriteLine("SID: " + queryObj["SID"]);
Console.WriteLine("SID Type: " + queryObj["SIDType"]);
Console.WriteLine("Status: " + queryObj["Status"]);
Console.WriteLine("");
}
}
catch (ManagementException err)
{
Console.WriteLine("An error occured while querying for WMI data: " + err.Message);
}
catch (System.UnauthorizedAccessException unauthorizedErr)
{
Console.WriteLine("Connection error " + "(user name or password might be incorrect): " + unauthorizedErr.Message);
}
There's a typo in the namespace path in your ManagementScope constructor:
ManagementScope scope = new ManagementScope(#"\\FullComputerName\\root\\CIMV2", connection);
The string should be either #"\\FullComputerName\root\CIMV2" or "\\\\FullComputerName\\root\\CIMV2".
Note that you cannot specify the user account for local connections. So if FullComputerName is a local computer, use this instead:
ManagementScope scope = new ManagementScope("root\\CIMV2");

ExecuteNonQuery Overflow Error ?

I've been trying to figure what is wrong with the code.
What I'm trying to do is that there are two Radiobuttons for gender, Male & Female...
I want that when Male radiobutton is clicked, the text MALE is saved into the database in the gender field which if of type text, but instead I'm getting an overflow error...
Before adding the radiobuttons and the [GENDER] field, everything was working fine...
So any help with it?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace OfflineRF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string gender;
private void button1_Click(object sender, EventArgs e)
{
string ORF1 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\\OfflineRF.mdb";
OleDbConnection conn = new OleDbConnection(ORF1);
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO OFFRF([Fname], [Lname], [NIC], [Gender], [HomeTel], [Cellphone], [Passengers], [From], [To])VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + textBox7.Text + textBox8.Text +"','"+gender+"','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + comboBox1.Text + "','" + comboBox2.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
System.Windows.Forms.MessageBox.Show("Form Saved Successfully !", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
textBox7.Text = "";
textBox8.Text = "";
comboBox1.SelectedIndex = -1;
comboBox2.SelectedIndex = -1;
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.Text == "Karachi")
{
comboBox2.Items.Clear();
comboBox2.Items.Add("Sukkur");
comboBox2.Items.Add("Hyderabad");
}
else if (comboBox1.Text == "Sukkur")
{
comboBox2.Items.Clear();
comboBox2.Items.Add("Karachi");
comboBox2.Items.Add("Hyderabad");
}
else
{
comboBox2.Items.Clear();
comboBox2.Items.Add("Karachi");
comboBox2.Items.Add("Sukkur");
}
}
private void Male_CheckedChanged(object sender, EventArgs e)
{
if (Male.Checked)
gender = "Male";
else
gender = "Female";
}
}
}
You have an infinite loop. When the combo box changes the selectedindex event is raised, then you change the combo box and the event fires again.
Edited...
At the end of the button event handler you are changing the combo box Indexes again causing an endless loop of event firing and the ensuing stackoverflow
Aside from the possibility of SQL-Injection by adding your values in a concatenated string, you could also be failing if someone were to put in a name value like "O'Conner" where the quote in the name would terminate the string and throw the rest off.
Look into OleDbParameter object and setting them. Without exact syntax you would do something like
string ORF1 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\\OfflineRF.mdb";
OleDbConnection conn = new OleDbConnection(ORF1);
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO OFFRF( Fname, Lname, NIC, Gender, HomeTel, "
+ "Cellphone, Passengers, [From], [To] ) VALUES "
+ "( ?, ?, ?, ?, ?, ?, ?, ?, ? )";
// Add parameters in same ordinal position as the "?" place-holders
// the first parameter is more of generic description of WHAT it is for and
// does NOT have to exactly match the column name, the second parameter is
// the actual value that should be put into the database. This same context
// is used for performing other SQL actions (select, delete, update, etc)
// to help prevent SQL injection.
cmd.Parameters.Add( "valForFName", textBox1.Text );
cmd.Parameters.Add( "valForLName", textBox2.Text );
cmd.Parameters.Add( "valForNIC", textBox3.Text + textBox7.Text + textBox8.Text );
// Not sure of syntax here, but get proper text from your radio choice of gender into string
gender = YourForm.RadioForGender.SelectedItem.Text;
cmd.Parameters.Add( "valForGender", gender );
cmd.Parameters.Add( "valHomePhone", textBox4.Text );
cmd.Parameters.Add( "valCell", textBox5.Text );
cmd.Parameters.Add( "howmany", textBox6.Text );
cmd.Parameters.Add( "forFromValue", comboBox1.Text );
cmd.Parameters.Add( "forToValue", comboBox2.Text );
cmd.ExecuteNonQuery();
conn.Close();

Resources