Fetch all data with particular sheet names - c#

Can you please anyone tell me how to Excel all data with particular sheet names insert in MS-SQL table. I am using C# code with MVC 5, This is my code C# and MVC 5
string path1 = #"c:\users\vaio\documents\visual studio 2013\Projects\test\Test2\Content\";
string fileFullPath = Path.GetFullPath(path1);
excelConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + fileFullPath + ";Extended Properties=\"text;HDR=YES;FMT=Delimited\"";
}
DataSet data = new DataSet();
foreach (var sheetName in GetExcelSheetNames(excelConnectionString))
{
using (OleDbConnection con = new OleDbConnection(excelConnectionString))
{
var dataTable = new DataTable(sheetName);
string query = string.Format("SELECT * FROM [{0}]", sheetName);
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(dataTable);
data.Tables.Add(dataTable);
using (TtestContext dc = new TtestContext())
{
for (int i = 0; i < dataTable.Tables[0].Rows.Count; i++)
{
string conn = ConfigurationManager.ConnectionStrings["TtestContext"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
string query2 = "Insert into ExcelTemps(Courier,F2,F3,F4,F5,F6,F7,F8,F9,F10) Values('"
+ dataTable.Tables[0].Rows[i][0].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][1].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][2].ToString().Replace("'", "''") + "' ,'"
+ dataTable.Tables[0].Rows[i][3].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][4].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][5].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][6].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][7].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][8].ToString().Replace("'", "''") + "','"
+ dataTable.Tables[0].Rows[i][9].ToString().Replace("'", "''") + "','"
+ dataTable + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query2, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
}
return View();
}
static string[] GetExcelSheetNames(string connectionString)
{
OleDbConnection con = null;
DataTable dt = null;
con = new OleDbConnection(connectionString);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheetNames;
}
}

Related

How to fix System.IndexOutOfRangeException: Cannot find table 0 ASP.NET

[WebMethod()]
public DataTable insert_data_to_db_from_local(string partnumber, string srctcode, string dockcode,int pack,string error,string chk,string user,DateTime day,string ekb,string kbid)
{
SqlConnection objConn = new SqlConnection();
SqlCommand objCmd = new SqlCommand();
SqlDataAdapter dtAdapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataTable dt = null;
string strConnString = null;
StringBuilder strSQL = new StringBuilder();
strConnString = "Server=localhost;UID=sa;PASSWORD=12345678;database=bds_pp_srct;Max Pool Size=400;Connect Timeout=600;";
strSQL.Append("INSERT INTO Hanheld (Part_Number,SRCT_Code,Dock_Code,Package,Error_Code,Chk_Type,LogUser,LogDate,ekb_order_no,Kanban_ID) VALUES ('" + partnumber + "','" + srctcode + "','" + dockcode + "','" + pack + "','" + error + "','" + chk + "','" + user + "','" + day + "','" + ekb + "','" + kbid + "') ");
//strSQL.Append(" WHERE [SRCT_Code] = '" + strCusID + "' ");
objConn.ConnectionString = strConnString;
var _with1 = objCmd;
_with1.Connection = objConn;
_with1.CommandText = strSQL.ToString();
_with1.CommandType = CommandType.Text;
dtAdapter.SelectCommand = objCmd;
dtAdapter.Fill(ds);
dt = ds.Tables[0];
dtAdapter = null;
objConn.Close();
objConn = null;
return dt;
}
This error :
System.IndexOutOfRangeException: Cannot find table 0.
at System.Data.DataTableCollection.get_Item(Int32 index)
Try this one
private DataTable dataTable = new DataTable();
string connString = #"query string here";
string query = "select table";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
conn.Close();
da.Dispose();
I think you are using DataSet in your code might be there would be a problem
so you first need to check where that DataSet contains datatable at 0 location
eg.
DataSet ds = new DataSet();
dtAdapter.Fill(ds);
if(ds != null && ds.Tables.Count > 0) {
//your logic
}
[WebMethod()]
public void insert_data_to_db_from_local(string partnumber, string srctcode, string dockcode)
{
using (SqlConnection conn = new SqlConnection("Server=localhost;UID=sa;PASSWORD=12345678;database=Test;Max Pool Size=400;Connect Timeout=600;"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"INSERT INTO Hanheld(Part_Number,SRCT_Code,Dock_Code) VALUES(#partnumber,#srctcode,#dockcode)";
cmd.Parameters.AddWithValue("#partnumber", partnumber);
cmd.Parameters.AddWithValue("#srctcode", srctcode);
cmd.Parameters.AddWithValue("#dockcode", dockcode);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
// MessgeBox.Show(e.Message.ToString(), "Error Message");
}
}
}
}
This my Be fixed

else condition not working when reader hasrows is false

Can somebody tell me why the else condition is not working in the code below.
The link button in asp.net web application has following code in code behind: a parameterized SqlCommand fetch a row from a SQL Server database, the SqlDataReader rdr1.HasRows in if condition is working fine but else condition did not work.
Code updated
protected void LinkButton1_Click(object sender, EventArgs e)
{
string comid = DropDownList4.SelectedValue.ToString();
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("Select * from Commercials Where id =" + comid, con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string dur = rdr["duration"].ToString();
Char delimiter = '/';
string[] dd = DateTime.Parse(rdr["rodate"].ToString()).ToString("dd/MM/yyyy").Split(delimiter);
if (DropDownList3.SelectedValue.ToString().Contains("BOL NEWS") == true && DropDownList1.SelectedValue.ToString().Contains("After Headlines") == true)
{
SqlConnection con0 = new SqlConnection(cs);
string sql01 = "Select * from CTS Where air_time=(Select max(air_time) from CTS where air_date=#airdate and air_time Like #airtime and channel=#channel and Slot=#slot) and air_date=#airdate1";
con0.Open();
SqlCommand cmd1 = new SqlCommand(sql01, con0);
cmd1.Parameters.AddWithValue("#airdate", TextBox1.Text);
cmd1.Parameters.AddWithValue("#channel", DropDownList3.SelectedValue.ToString());
cmd1.Parameters.AddWithValue("#airtime", DropDownList2.SelectedValue.ToString().Substring(0, 2) + "%");
cmd1.Parameters.AddWithValue("#slot", DropDownList1.SelectedValue.ToString().Remove(0, 3));
cmd1.Parameters.AddWithValue("#airdate1", TextBox1.Text);
SqlDataReader rdr1 = cmd1.ExecuteReader();
while (rdr1.Read())
{
string startTime0 = rdr1["air_time"].ToString();
string addsec = rdr1["duration"].ToString();
if (rdr1.HasRows)
{
DateTime startTime1 = DateTime.ParseExact(startTime0, "HH:mm:ss", null);
string startHeadlines_ = startTime1.AddSeconds(int.Parse(addsec)).ToString("HH:mm:ss");
using (SqlConnection con2 = new SqlConnection(cs))
{
string type = "Commercial";
string year = dd[2].ToString().Substring(dd[2].ToString().Length - 2);
string HouseId = "CH1COM001" + rdr["rono"] + rdr["duration"] + "S" + dd[1] + dd[0] + year;
string sql1 = "Insert into CTS(air_date,air_time,HouseNumber,rono,Title,duration,Slot,type,channel)Values('" + TextBox1.Text + "','" + startHeadlines_ + "','" + HouseId + "','" + rdr["rono"] + "','" + rdr["slug"] + "','" + rdr["duration"] + "','" + DropDownList1.SelectedValue.Remove(0, 3) + "','" + type + "','" + DropDownList3.SelectedValue.ToString() + "')";
con2.Open();
SqlCommand InsertCmd = new SqlCommand(sql1, con2);
InsertCmd.ExecuteNonQuery();
con2.Close();
}
}
else
{
DateTime startTime = DateTime.ParseExact(DropDownList2.SelectedValue.ToString(), "HH:mm:ss", null);
string startHeadlines = startTime.AddSeconds(210).ToString("HH:mm:ss");
using (SqlConnection con1 = new SqlConnection(cs))
{
string type = "Commercial";
string year = dd[2].ToString().Substring(dd[2].ToString().Length - 2);
string HouseId = "CH1COM001" + rdr["rono"] + rdr["duration"] + "S" + dd[1] + dd[0] + year;
string sql = "Insert into CTS(air_date,air_time,HouseNumber,rono,Title,duration,Slot,type,channel)Values('" + TextBox1.Text + "','" + startHeadlines + "','" + HouseId + "','" + rdr["rono"] + "','" + rdr["slug"] + "','" + rdr["duration"] + "','" + DropDownList1.SelectedValue.ToString().Remove(0, 3) + "','" + type + "','" + DropDownList3.SelectedValue.ToString() + "')";
con1.Open();
SqlCommand InsertCmd = new SqlCommand(sql, con1);
InsertCmd.ExecuteNonQuery();
con1.Close();
}
}
}
con0.Close();
}
}
con.Close();
}
}

C# SQLite database locked

I've tried all the solutions I could find to this problem, but for some reason I still get an exception stating the database I'm using is locked.
My code is as follows:
string connectionString = "Data Source=D:\\CCIW\\LCM\\Organisational Database\\OrganisationalDB;" +
"MultipleActiveResultSets=True";
using (SQLiteConnection OriginatorDBConnection = new SQLiteConnection(connectionString))
{
string originatorName, originatorOrganisation, originatorAddress, originatorCellNumber, originatorTelNumber, originatorEmail;
originatorName = originatorNameTextBox.Text;
originatorOrganisation = originatorOrganisationTextBox.Text;
originatorAddress = originatorAddressRichTextBox.Text;
originatorCellNumber = originatorCellTextBox.Text;
originatorTelNumber = originatorTelTextBox.Text;
originatorEmail = originatorEmailTextBox.Text;
OriginatorDBConnection.Open();
string originatorINSERT = "INSERT INTO Originator (Name, Organisation, Address, CellphoneNumber, TelephoneNumber, Email) VALUES ('" + originatorName + "', '" + originatorOrganisation + "', '" + originatorAddress + "', '" + originatorCellNumber + "', '" + originatorTelNumber + "', '" + originatorEmail + "');";
using (SQLiteCommand originatorCommand = new SQLiteCommand(originatorINSERT, OriginatorDBConnection))
{
originatorCommand.ExecuteNonQuery();
}
OriginatorDBConnection.Close();
}
The closest solution on here that I could find to the problem was here: SQLite Database Locked exception
It didn't seem to work on my problem, however.
What am I doing wrong?
I have an additional function wherein I use the connection:
public AdminForm()
{
//Initialise AdminForm components.
InitializeComponent();
//Establish and open connection to ObservationDB.
string connectionString = "Data Source=D:\\CCIW\\LCM\\Organisational Database\\OrganisationalDB;" +
"MultipleActiveResultSets=True";
ObservationDBConnection = new SQLiteConnection(connectionString);
ObservationDBConnection.Open();
//Query database to find all originators
string originatorSELECT = "SELECT * FROM Originator;";
string ECPNumberSELECT = "SELECT * FROM ECP";
SQLiteCommand command = new SQLiteCommand(originatorSELECT, ObservationDBConnection);
SQLiteDataReader reader = command.ExecuteReader();
SQLiteCommand command2 = new SQLiteCommand(ECPNumberSELECT, ObservationDBConnection);
SQLiteDataReader reader2 = command2.ExecuteReader();
//Populate OriginatorName combobox with names of existing originators.
List<string> originatorNames = new List<string>();
while (reader.Read())
{
originatorNames.Add(Convert.ToString(reader["Name"]));
}
OriginatorNameComboBox.DataSource = originatorNames;
//Populate ECP combobox with numbers of existing ECP.
List<string> ECPNumbers = new List<string>();
while (reader2.Read())
{
ECPNumbers.Add(Convert.ToString(reader2["Number"]));
}
ECPNumComboBox.DataSource = ECPNumbers;
//Populate TC Decision combobox with options.
List<string> TCDecision = new List<string>();
TCDecision.Add("Rework");
TCDecision.Add("Reject");
TCDecision.Add("Approve");
TCDecisionComboBox.DataSource = TCDecision;
ObservationDBConnection.Close();
}
And here:
private void SaveButton_Click(object sender, EventArgs e)
{
ObservationDBConnection.Open();
...
string ImpactTypeINSERT = "INSERT INTO ImpactType (ImpactType, Description) VALUES ('" + impactType + "', '" + impactDescription + "');";
SQLiteCommand ImpactTypeCommand = new SQLiteCommand(ImpactTypeINSERT, ObservationDBConnection);
//SQLiteDataReader ImpactTypeReader = ImpactTypeCommand.ExecuteReader();
ImpactTypeCommand.ExecuteNonQuery();
...
string TCDecisionINSERT = "INSERT INTO TCDecision (Decision, Description) VALUES ('" + TechnicalCommitteeDecision + "', '" + TechnicalCommitteeDescription + "');";
SQLiteCommand TCDecisionCommand = new SQLiteCommand(TCDecisionINSERT, ObservationDBConnection);
SQLiteDataReader TCDecisionReader = ImpactTypeCommand.ExecuteReader();
TCDecisionCommand.ExecuteNonQuery();
...
string OperationalDecisionINSERT = "INSERT INTO OperationalDecision (Decision, Description) VALUES ('" + operationalDecision + "', '" + operationalDescription + "');";
SQLiteCommand OperationalDecisionCommand = new SQLiteCommand(OperationalDecisionINSERT, ObservationDBConnection);
//SQLiteDataReader OperationalDecisionReader = OperationalDecisionCommand.ExecuteReader();
OperationalDecisionCommand.ExecuteNonQuery();
...
...
string OriginatorIDSELECT = "SELECT * FROM Originator WHERE Name='" + OriginatorNameComboBox.Text + "';";
SQLiteCommand OriginatorIDCommand = new SQLiteCommand(OriginatorIDSELECT, ObservationDBConnection);
SQLiteDataReader OriginatorIDReader = OriginatorIDCommand.ExecuteReader();
originatorIDOBS = OriginatorIDReader.GetOrdinal("ID");
//ImpactType
string impactTypeSELECT = "SELECT * FROM ImpactType WHERE ImpactType='" + impactType + "';";
SQLiteCommand impactTypeOBSCommand = new SQLiteCommand(impactTypeSELECT, ObservationDBConnection);
SQLiteDataReader impactTypeOBSReader = impactTypeOBSCommand.ExecuteReader();
impactTypeOBS = impactTypeOBSReader.GetOrdinal("ID");
string operationalDecisionOBSSELECT = "SELECT * FROM OperationalDecision WHERE Decision='" + operationalDecision + "';";
SQLiteCommand operationalDecisionOBSCommand = new SQLiteCommand(operationalDecisionOBSSELECT, ObservationDBConnection);
SQLiteDataReader operationalDecisionOBSReader = operationalDecisionOBSCommand.ExecuteReader();
operationalDecisionOBS = operationalDecisionOBSReader.GetOrdinal("ID");
...
string ECPOBSSELECT = "SELECT * FROM ECP WHERE Number='" + ECPNumComboBox.Text + "';";
SQLiteCommand ECPCommand = new SQLiteCommand(ECPOBSSELECT, ObservationDBConnection);
SQLiteDataReader ECPReader = ECPCommand.ExecuteReader();
ECPOBS = ECPReader.GetOrdinal("ID");
string CNISObservationINSERT = "INSERT INTO CNISObservation (Title, ReceiveDate, TableDate, OriginatorID, OriginatorReference, OriginatorDate, ObservationNumber, RevisionNumber, Description, Status, ImpactDescription, ImpactType, OperationalRequirementDescription, OperationalImpact, OperationalDecision, ProposedAction, TCDecision, ECP, SolutionOperationalImpact, TechnicalSolutionImpact) VALUES ('" +
titleOBS + "','"
+ receiveDateOBS + "','"
+ tableDateOBS + "','"
+ originatorIDOBS + ",'"
+ originatorReferenceOBS +"','"
+ originatorDateOBS + "','"
+ observationNumberOBS + "',"
+ revisionNumberOBS + ",'"
+ descriptionOBS + "',"
+ statusOBS + ",'"
+ impactDescriptionOBS + "',"
+ impactTypeOBS + ",'"
+ operationalRequirementDescriptionOBS + "','"
+ operationalImpactOBS + "',"
+ operationalDecisionOBS + ",'"
+ TCDecisionOBS + ","
+ ECPOBS + ",'"
+ solutionOperationalImpactOBS + "','"
+ technicalSolutionImpactOBS + "');";
...
string obsOBSSELECT = "SELECT * FROM CNISObservation ORDER BY ID DESC LIMIT 1;";
SQLiteCommand CNISObservationIDCommand = new SQLiteCommand(obsOBSSELECT, ObservationDBConnection);
SQLiteDataReader CNISObservationIDReader = CNISObservationIDCommand.ExecuteReader();
observationID = CNISObservationIDReader.GetOrdinal("ID");
...
foreach (var capabilityID in capabilitiesSelected)
{
string ObservationOperationalCapabilitiesINSERT = "INSERT INTO ObservationOperationalCapabilities (CapabilityID, ObservationID) VALUES (" + capabilityID + "," + observationID + ");";
SQLiteCommand ObservationOperationalCapabilitiesCommand = new SQLiteCommand(ObservationOperationalCapabilitiesINSERT, ObservationDBConnection);
// SQLiteDataReader ObservationOperationalCapabilitiesReader = ObservationOperationalCapabilitiesCommand.ExecuteReader();
ObservationOperationalCapabilitiesCommand.ExecuteNonQuery();
}
...
string CNISObservationIDSELECT = "SELECT * FROM CNISObservation ORDER BY ID DESC LIMIT 1;";
SQLiteCommand CNISObservationCommand = new SQLiteCommand(CNISObservationIDSELECT, ObservationDBConnection);
SQLiteDataReader CNISObservationReader = CNISObservationCommand.ExecuteReader();
CNISObservationID = CNISObservationReader.GetOrdinal("ID");
string CNISReleaseINSERT = "INSERT INTO CNISSection VALUES (" + CNISObservationID + "," + CNISRelease + "," + chapter + ",'" + paragraph + "','" + section + "','" + page +"');";
SQLiteCommand CNISReleaseCommand = new SQLiteCommand(CNISReleaseINSERT, ObservationDBConnection);
//SQLiteDataReader CNISReleaseReader = CNISReleaseCommand.ExecuteReader();
CNISReleaseCommand.ExecuteNonQuery();
ObservationDBConnection.Close();
}
I know I'm a lot late to the game, but it looks like you're not closing you reader variables in AdminForm() constructor. Consider wrapping the DataReaders in a using().
Wrapping around Command and Reader did work for me:
using (SqliteCommand cmd = new SqliteCommand(sQuery, m_Conn))
{
using (SqliteDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
ret_type = reader.GetInt32(0);
}
}
}
Please be aware to click on Write changes on SQLite browser if it is running and there are any unsaved changes!
In my case it was very stupid of me, I was making changes in SQLite browser and did not click on write changes, which locked the DB to be modified by the services. After I clicked the Write changes button, all the post request worked as expected.
According to #Rohan Shenoy in this topic: SQLite Database Locked exception

how to save imported excel in datagridview to database C#

how to save imported data from excel in datagridview to database in C#
I have saved records and exported to excel sheet, it exported along with data ID, now I have re-imported back to datagridview from excel. now I want to save data to database.
Important to know:
Database name "Records.sdf" using SQL Compact 3.5
DataGridViewName is RecordsDataGridView.
I'm using following code but it's not working.
public void SaveData()
{
// Save the data.
SqlCeConnection conn =
new SqlCeConnection(
#"Data Source=|DataDirectory|\Records.sdf;Persist Security Info=False");
SqlCeCommand com;
string str;
conn.Open();
for (int index = 0; index < RecordsDataGridView.Rows.Count - 1; index++)
{
str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values(" + RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ", '" + RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "'," + RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[8].Value.ToString() + ")";
com = new SqlCeCommand(str, conn);
com.ExecuteNonQuery();
}
conn.Close();
}
ERROR RECEIVING
Column Name not Valid, column name = Cash
Try this query string
str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values(" + RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ",'"+ RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "'," + RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + ",'" + RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[8].Value.ToString() + "')";
You should pass varchar field enclosed with single quote.
var str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values("
+ RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ", '"
+ RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "',"
+ RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + ","
+ "'" + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "'" + ","
+ RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + ","
+ "'" + dataGridView1.Rows[index].Cells[8].Value.ToString() + "'" + ")";
There are a few ways to do this.
Here is one method.
private void save_btn_Click(object sender, EventArgs e)
{
sAdapter.Update(sTable);
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
new_btn.Enabled = true;
delete_btn.Enabled = true;
}
http://csharp.net-informations.com/datagridview/csharp-datagridview-database-operations.htm
You can do this as well.
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
StrQuery= #"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
Something like this will work too.
private void buttonSave_Click_1(object sender, EventArgs e) // save to invoice
{
SqlConnection con = new SqlConnection(MyConnectionString);
string SqlCmdText = "INSERT INTO invoice (p_code, p_name, p_category, p_price) " +
VALUES (#code, #name, #category, #price)";
SqlCommand sc = new SqlCommand(SqlCmdText, con);
con.Open();
foreach (DataRow row in MyTable.Rows)
{
sc.Parameters.Clear();
sc.Parameters.AddWithValue("#code", row["p_code"]);
sc.Parameters.AddWithValue("#name", row["p_name"]);
sc.Parameters.AddWithValue("#category", row["p_category"]);
sc.Parameters.AddWithValue("#price", row["p_price"]);
sc.ExecuteNonQuery();
}
con.Close();
}

import xml to mdb

I'm trying to export a SQL-Server query to an XML file now and I want to import that file to Access. I don't understand how to do this.
Here is the code I use to generate the XML:
protected void Button1_Click(object sender, EventArgs e) {
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlSconn"].ConnectionString);
con.Open();
string strSQL = "select * from dbo.table_"+test.Text.ToString()+"";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
DataSet ds = new DataSet();
dt.Fill(ds, "" + test.Text.ToString() + "");
ds.WriteXml(Server.MapPath("temp.xml"));
}
This may be a start.
static void SaveToMDB(DataSet ds, string strMDBFile)
{
OleDbConnection cAccess = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strMDBFile);
cAccess.Open();
foreach (DataTable oTable in ds.Tables)
{
OleDbCommand oCommand = new OleDbCommand(
"DROP TABLE [" + oTable.TableName + "]", cAccess);
try
{
oCommand.ExecuteNonQuery();
}
catch (Exception) { }
string strCreateColumns = "";
string strColumnList = "";
string strQuestionList = "";
foreach (DataColumn oColumn in oTable.Columns)
{
strCreateColumns += "[" + oColumn.ColumnName + "] VarChar(255), ";
strColumnList += "[" + oColumn.ColumnName + "],";
strQuestionList += "?,";
}
strCreateColumns = strCreateColumns.Remove(strCreateColumns.Length - 2);
strColumnList = strColumnList.Remove(strColumnList.Length - 1);
strQuestionList = strQuestionList.Remove(strQuestionList.Length - 1);
oCommand = new OleDbCommand("CREATE TABLE [" + oTable.TableName
+ "] (" + strCreateColumns + ")", cAccess);
oCommand.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter(
"SELECT * FROM [" + oTable.TableName + "]", cAccess);
da.MissingSchemaAction = MissingSchemaAction.Add;
da.FillLoadOption = LoadOption.OverwriteChanges;
da.InsertCommand = new OleDbCommand(
"INSERT INTO [" + oTable.TableName + "] (" + strColumnList
+ ") VALUES (" + strQuestionList + ")", cAccess);
foreach (DataColumn oColumn in oTable.Columns)
{
da.InsertCommand.Parameters.Add(
oColumn.ColumnName,
OleDbType.VarChar,
255,
oColumn.ColumnName
);
}
foreach (DataRow oRow in oTable.Rows)
oRow.SetAdded();
da.Update(oTable);
}
}
This Data will work only with ID and Name, using the system :
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data.Sql;using System.Data.SqlClient;using System.Configuration;using System.Data;using System.IO;
using System.Xml.Linq;
//import SelectiveDatabaseBackup.xml to test9 table
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices3"].ConnectionString;
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
ds.ReadXml(XDocument.Load("c:/d/SelectiveDatabaseBackup.xml").CreateReader());
foreach (DataTable table in ds.Tables)
{
//Create table
foreach (DataRow row in table.Rows)
{
string name = row[1].ToString();
string id = row[0].ToString();
cmd.CommandText = "INSERT test9 VALUES ('"+ id +"','"+ name + "')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
//--------------------------

Categories

Resources