private void BindGrid() { var ds = new DataSet(); var cs = ConfigurationManager.ConnectionStrings["Msts"].ConnectionString; var cnn = new SqlConnection(cs); var cmd = new SqlCommand("select * from jobs", cnn) { CommandType = CommandType.Text }; var sa = new SqlDataAdapter(cmd) { UpdateBatchSize = 3 }; var scb = new SqlCommandBuilder(sa); sa.RowUpdated += (x, y) => { this.msg.Text += "<br />Rows updated: " + y.RecordsAffected.ToString(); }; sa.Fill(ds, "jobs"); this.gvpicker.DataSource = (from DataRow j in ds.Tables["jobs"].Rows where j.Field<string>("job_desc").Contains("a") select j).CopyToDataTable().DefaultView; this.gvpicker.DataBind(); foreach (DataRow item in ds.Tables["jobs"].Rows) { item["job_desc"] = item["job_desc"].ToString() + "plop"; } sa.Update(ds, "jobs"); foreach (DataRow item in ds.Tables["jobs"].Rows) { item["job_desc"] = item["job_desc"].ToString().Replace("plop", string.Empty); } sa.Update(ds, "jobs"); }
public static void DataAdapterExample() { var connectionString = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString; using (var sqlConnection = new SqlConnection(connectionString)) { var sqlCommandText = "SELECT * FROM BrokenCars;"; var dataAdapter = new SqlDataAdapter(sqlCommandText, sqlConnection); var dataTable = new DataTable(); dataAdapter.Fill(dataTable); var insertText = "INSERT INTO BrokenCars(name) VALUES(@Name)"; var insertCommand = new SqlCommand(insertText, sqlConnection); insertCommand.Parameters.Add("@Name", SqlDbType.VarChar, 255, "name"); dataAdapter.InsertCommand = insertCommand; var row = dataTable.NewRow(); row["Name"] = "ZAZ"; dataTable.Rows.Add(row); dataAdapter.Update(dataTable); //var deleteRow = dataTable.Rows[4]; //dataTable.Rows.Remove(deleteRow); //dataAdapter.Update(dataTable); sqlConnection.Open(); var delFromTable = @"DELETE FROM BrokenCars WHERE ID > 4;"; var delCommand = new SqlCommand(delFromTable, sqlConnection); dataAdapter.DeleteCommand = delCommand; dataAdapter.DeleteCommand.ExecuteNonQuery(); dataAdapter.Update(dataTable); } }
private void delete_button_Click(object sender, EventArgs e) { if (DialogResult.Yes == MessageBox.Show("是否确定要删除该数据!", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2)) { try { int RowID = dataGridView1.CurrentRow.Index; string tablename = m_dic_meta_info_Table.Rows[RowID][0].ToString(); string fieldname = m_dic_meta_info_Table.Rows[RowID][1].ToString(); string sqltxt = "DELETE FROM sys_meta_info WHERE (tablename = '" + tablename + "') AND (fieldname = '" + fieldname + "')"; m_adp.DeleteCommand = new SqlCommand(sqltxt, m_conn); m_dic_meta_info_Table.Rows[RowID].Delete(); m_adp.Update(m_dic_meta_info_Table); MessageBox.Show("数据删除成功!", "删除信息"); m_dic_meta_info_Table.AcceptChanges(); } catch (SqlException ex) { MessageBox.Show(ex.ToString()); } } }
public bool UpdateAdmins(DataSet ds) { try { using (SqlConnection conn = new SqlConnection(DbConnection.connectionString)) { //declare adapter SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * from Admins", conn); //set commands dataAdapter.UpdateCommand = new SqlCommand("Update Admins Set" + " Password = @Password, Salt = @Salt" + " Where Username = @Username", conn); dataAdapter.DeleteCommand = new SqlCommand("delete from Admins where Username = @Username", conn); dataAdapter.InsertCommand = new SqlCommand("insert into Admins values(@Username, @password, @Salt)", conn); //add parameters dataAdapter.UpdateCommand.Parameters.Add("@Password", SqlDbType.Char, 100, "Password"); dataAdapter.UpdateCommand.Parameters.Add("@Salt", SqlDbType.Char, 50, "Salt"); dataAdapter.InsertCommand.Parameters.Add("@Username", SqlDbType.Char, 50, "Username"); dataAdapter.InsertCommand.Parameters.Add("@Password", SqlDbType.Char, 100, "Password"); dataAdapter.InsertCommand.Parameters.Add("@Salt", SqlDbType.Char, 50, "Salt"); //add sql parameters SqlParameter parameter = dataAdapter.UpdateCommand.Parameters.Add("@Username", SqlDbType.Char); parameter.SourceColumn = "Username"; parameter.SourceVersion = DataRowVersion.Original; SqlParameter parameter2 = dataAdapter.DeleteCommand.Parameters.Add("@Username", SqlDbType.Char); parameter2.SourceColumn = "Username"; parameter2.SourceVersion = DataRowVersion.Original; //execute delete and update int deleted = dataAdapter.Update(ds.Tables[0].Select(null, null, DataViewRowState.Deleted)); int updated = dataAdapter.Update(ds.Tables[0].Select(null, null, DataViewRowState.ModifiedCurrent)); int added = dataAdapter.Update(ds.Tables[0].Select(null, null, DataViewRowState.Added)); //if nothing was updated return false if (deleted == 0 && updated == 0 && added == 0) return false; } return true; } catch (Exception e) { Console.WriteLine(e); return false; } }
/// <summary> /// Thêm mới kiểu hợp đồng /// </summary> /// <param name="dsContractType"></param> /// <returns></returns> public int AddContractTypeDO(DataSet dsDayType) { conn = WorkingContext.GetConnection(); sqlCommand = new SqlCommand("AddContractType",conn); sqlCommand.CommandType = CommandType.StoredProcedure; //sqlCommand.Parameters.Add(WorkingContext.CreateParam("@ContractID",SqlDbType.Int ,"ContractID")); sqlCommand.Parameters.Add(WorkingContext.CreateParam("@ContractName",SqlDbType.NVarChar ,"ContractName")); sqlCommand.Parameters.Add(WorkingContext.CreateParam("@InsurancePay", SqlDbType.Bit, "InsurancePay")); sqlCommand.Parameters.Add(WorkingContext.CreateParam("@Note",SqlDbType.NVarChar,"Note")); SqlParameter result = new SqlParameter("@ReturnValue",SqlDbType.Int); result.Direction = ParameterDirection.ReturnValue; sqlCommand.Parameters.Add(result); dadapter = new SqlDataAdapter(); dadapter.InsertCommand = sqlCommand; try { conn.Open(); dadapter.Update(dsDayType,"tblContract"); return (int)result.Value; } catch (Exception ex) { MessageBox.Show(ex.ToString()); return 0; } finally { conn.Dispose(); conn.Close(); } }
static void Main(string[] args) { string connectionString = ConfigurationManager.ConnectionStrings["Nordwind"].ConnectionString; SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Categories", connectionString); DataSet dataSet = new DataSet(); adapter.Fill(dataSet); //foreach (DataRow row in dataSet.Tables[0].Rows) //{ // // Delete Row // if ((int)row[0] == 10) { // dataSet.Tables[0].Rows.Remove(row); // dataSet.Tables[0].AcceptChanges(); // adapter.Update(dataSet); // break; // } //} // Insert row DataRow newCategory = dataSet.Tables[0].NewRow(); newCategory["CategoryName"] = "Suplies"; newCategory["Description"] = "Some stuff"; dataSet.Tables[0].Rows.Add(newCategory); dataSet.Tables[0].AcceptChanges(); adapter.Update(dataSet); Console.WriteLine("Categories sucessfully updated"); Console.ReadLine(); }
public static bool AppendDataTable(ref DataTable dsNewTable, string strSQL) { if (!OpenConnection()) { return(false); } try { DataTable oDataSet = new DataTable(); System.Data.SqlClient.SqlDataAdapter DataAdapter; DataAdapter = new System.Data.SqlClient.SqlDataAdapter(strSQL, lo_Connection); System.Data.SqlClient.SqlCommandBuilder myDataRowsCommandBuilder = new System.Data.SqlClient.SqlCommandBuilder(DataAdapter); DataAdapter.Update(dsNewTable); DataAdapter.Dispose(); myDataRowsCommandBuilder.Dispose(); return(true); } catch { return(false); } finally { lo_Connection.Close(); } }
/// <summary> /// 保存数据表所做的更改(带事务) /// </summary> /// <param name="conn">SqlTransaction</param> /// <param name="trans">SqlTransaction</param> /// <param name="strSQL">需要更新的表的SQL语句</param> /// <param name="dt">需要更新的DataTable</param> public static void SaveChangesOnTrans(SDC.SqlConnection conn, SDC.SqlTransaction trans, string strSQL, SD.DataTable dt) { //this.Validate(); try { using (sqlcmd = new SDC.SqlCommand(strSQL, conn, trans)) { using (sqladp = new SDC.SqlDataAdapter(sqlcmd)) { //sqladp.InsertCommand.Transaction = trans; using (sqlcmdbd = new SDC.SqlCommandBuilder(sqladp)) { sqlcmdbd.ConflictOption = SD.ConflictOption.CompareRowVersion; sqladp.InsertCommand = sqlcmdbd.GetInsertCommand(); sqladp.UpdateCommand = sqlcmdbd.GetUpdateCommand(); sqladp.DeleteCommand = sqlcmdbd.GetDeleteCommand(); sqladp.Update(dt); } } } } catch (SDC.SqlException ex) { throw ex; } catch (Exception ex) { throw ex; } }
public static int ExecuteNonQuery(string connectionString, string cmdText, DataSet ds, string s, params SqlParameter[] commandParameters) { // Create a new Sql command SqlCommand cmd = new SqlCommand(); //Create a connection using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); //Prepare the command cmd.CommandText = cmdText; cmd.Connection = connection; cmd.CommandType = CommandType.StoredProcedure; foreach (SqlParameter e in commandParameters) { cmd.Parameters.Add(e); } SqlDataAdapter da = new SqlDataAdapter(); da.InsertCommand = cmd; //Execute the command int val = da.Update(ds, s); connection.Close(); cmd.Parameters.Clear(); return val; } }
static void Main(string[] args) { // string connectionString = @"data source=(localDB)\v11.0; Initial catalog=TrainingDB; integrated security=SSPI"; //string connectionString = "data source=192.168.20.125;database=SMSDB;Integrated Security=false; user id=sa; password=leads@123"; string connectionString = @"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\TrainingDB.mdf;Initial Catalog=TrainingDB;Integrated Security=True"; string commandString = @"SELECT * FROM Shippers"; SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, connectionString); SqlCommandBuilder scb = new SqlCommandBuilder(dataAdapter); DataSet myDataSet = new DataSet(); dataAdapter.Fill(myDataSet, "Shippers"); DataTable sTable = myDataSet.Tables["Shippers"]; // add data object[] o = { 1, "General", "555-1212" }; sTable.Rows.Add(o); dataAdapter.Update(myDataSet, "Shippers"); myDataSet.AcceptChanges(); Console.ReadKey(); }
private void button1_Click(object sender, EventArgs e) { String SQLQuery = @"SELECT [guid] ,[WCName] ,[MachineState] ,[StartTime] ,[EndTime] ,[LastModified] FROM [SFI_local_PC_SQL].[dbo].[tbl_slc_MachineStateHistory] WHERE [EndTime] IS NULL"; using (SqlConnection con = new SqlConnection("Data Source=" + Settings1.SQLConnectionString + ";Initial Catalog=SFI_local_PC_SQL;Integrated Security=True")) { con.Open(); using (SqlDataAdapter da = new SqlDataAdapter(SQLQuery, con)) { using (SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da)) { DataSet DataSet1 = new DataSet(); da.Fill(DataSet1, "tbl_slc_MachineStateHistory"); DataSet1.Tables["tbl_slc_MachineStateHistory"].Rows[0]["MachineState"] = 0; da.Update(DataSet1, "tbl_slc_MachineStateHistory"); } } } }
protected void Add_Click(object sender, EventArgs e) { DateTime dt = DateTime.Now; SqlCommand cmd = new SqlCommand(); cmd.CommandText = "select * from Company"; cmd.Connection = con; SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = cmd; DataSet ds = new DataSet(); da.Fill(ds, "Company"); SqlCommandBuilder cb = new SqlCommandBuilder(da); DataRow drow = ds.Tables["Company"].NewRow(); drow["User_Id"] = UserId.Text; drow["Category"] = Category.SelectedItem; drow["Person"] = ContactPerson.Text; drow["C_Name"] = CompanyName.Text; drow["Mobile_No"] = Mobile.Text; drow["Tagline"] = Tagline.Text; drow["Phone"] = Phone.Text; drow["Email_Id"] = Email.Text; drow["Website"] = Website.Text; drow["Date"] = dt.ToShortDateString(); drow["Address"] = Address1.Text; drow["Shop"] = Shop.Text; drow["Gali"] = Gali.Text; ds.Tables["Company"].Rows.Add(drow); da.Update(ds, "Company"); Panel1.Visible = false; Panel2.Visible = true; }
public void BorrarPersonal(ArrayList arraydni) { DataSet dsPersonal = new DataSet(); try { string frase=""; for (int i = 0; i < arraydni.Count; i++) { if (i == 0){ frase += "'" + arraydni[i] + "'"; } else { frase += ","; frase += "'" + arraydni[i] + "'"; } } SqlConnection conexion = new SqlConnection(cadenaConexion); String consulta = "Select * from Personal where DNI in ("+frase+")"; SqlDataAdapter daPersonal = new SqlDataAdapter(consulta, conexion); daPersonal.MissingSchemaAction = MissingSchemaAction.AddWithKey; daPersonal.Fill(dsPersonal, nombreTabla); for (int i = 0; i < arraydni.Count; i++)//lo hacemos parar borrar las filas que corresponden con los dnis { dsPersonal.Tables["Personal"].Rows[i].Delete(); } SqlCommandBuilder cbuilder = new SqlCommandBuilder(daPersonal); daPersonal.Update(dsPersonal, "Personal"); } catch (Exception ex) { throw (ex); } }
private void btnSave_Click(object sender, System.EventArgs e) { if (this.txtRoomID.Text.Trim() == "" || this.txtTypeID.Text.Trim() == "" || this.txtNum.Text.Trim() == "" || this.txtBedNum.Text.Trim() == "") { MessageBox.Show("客房编号、类型编号、额定人数、床数不能空"); } else { try { HotelDataSet.客房信息Row dr = ds.客房信息.New客房信息Row(); dr.客房编号 = this.txtRoomID.Text.Trim(); dr.类型编号 = this.txtTypeID.Text.Trim(); dr.客房类型 = this.txtRoomType.Text.Trim(); dr.客房位置 = this.txtPlace.Text.Trim(); dr.额定人数 = Int32.Parse(this.txtNum.Text.Trim()); dr.床数 = Int32.Parse(this.txtBedNum.Text.Trim()); dr.客房描述 = this.txtSay.Text.Trim(); dr.状态 = this.txtState.Text.Trim(); dr.是否可拼房 = this.checkBox1.Checked; this.ds.客房信息.Add客房信息Row(dr); da.Update(ds, "客房信息"); MessageBox.Show("数据保存成功"); } catch (Exception ex) { MessageBox.Show("输入有误" + ex.Message.ToString()); } } }
/// <summary> /// Thêm thời gian làm việc theo nhan vien /// </summary> /// <param name="dataSet"></param> /// <returns></returns> public int AddWorkingTime(DataSet dataSet) { SqlConnection conn = WorkingContext.GetConnection(); // Build the command SqlCommand sqlCommand = new SqlCommand("AddWorkingTime", conn); sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.Add(WorkingContext.CreateParam("@EmployeeID", SqlDbType.Int, "EmployeeID")); sqlCommand.Parameters.Add(WorkingContext.CreateParam("@Day", SqlDbType.DateTime, "Day")); sqlCommand.Parameters.Add(WorkingContext.CreateParam("@ShiftID", SqlDbType.Int, "ShiftID")); sqlCommand.Parameters.Add(WorkingContext.CreateParam("@TimeSheet", SqlDbType.Float, "TimeSheet")); SqlDataAdapter dataAdapter = new SqlDataAdapter(); dataAdapter.InsertCommand = sqlCommand; try { conn.Open(); return dataAdapter.Update(dataSet.Tables[0]); } catch(Exception oException) { MessageBox.Show(oException.ToString()); return 0; } finally { conn.Dispose(); conn.Close(); } }
/// <summary> /// Thêm lịch sử phòng ban mới /// </summary> /// <param name="dataSet"></param> /// <returns></returns> public int AddDepartmentHistory(DataSet dataSet) { SqlConnection conn = WorkingContext.GetConnection(); // Build the command SqlCommand sqlCommand = new SqlCommand("AddDepartmentHistory", conn); sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.Add(WorkingContext.CreateParam("@EmployeeID", SqlDbType.Int, "EmployeeID")); sqlCommand.Parameters.Add(WorkingContext.CreateParam("@DepartmentID", SqlDbType.Int, "DepartmentID")); sqlCommand.Parameters.Add(WorkingContext.CreateParam("@DecisionNumber", SqlDbType.NVarChar, "DecisionNumber")); sqlCommand.Parameters.Add(WorkingContext.CreateParam("@ModifiedDate", SqlDbType.DateTime, "ModifiedDate")); sqlCommand.Parameters.Add(WorkingContext.CreateParam("@Note", SqlDbType.NVarChar, "Note")); SqlDataAdapter dataAdapter = new SqlDataAdapter(); dataAdapter.InsertCommand = sqlCommand; try { conn.Open(); return dataAdapter.Update(dataSet.Tables[0]); } catch (Exception oException) { MessageBox.Show(oException.ToString()); return 0; } finally { conn.Dispose(); conn.Close(); } }
public void insert(customer_class cc) { SqlConnection con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=egas;Integrated Security=True;Pooling=False"); SqlDataAdapter da = new SqlDataAdapter("select * from customer",con); DataSet ds = new DataSet(); da.Fill(ds,"customer"); DataRow dr = ds.Tables[0].NewRow(); dr[0] = cc._id; dr[1] = cc._name; dr[2] = cc._father; dr[3] = cc._address; dr[4] = "empty"; dr[5] = cc._email; dr[6] = cc._contact; dr[7] = cc._dob; dr[8] = cc._pin; dr[9] = cc._dist; dr[10] = cc._dealer_id; dr[11] = 0; dr[12] = 6; dr[13] = "PENDING"; dr[14] = DateTime.Today.ToString("dd/MM/yyyy") ; ds.Tables[0].Rows.Add(dr); SqlCommandBuilder cb = new SqlCommandBuilder(da); da.Update(ds.Tables[0]); }
public void TestBook() { try { DBManager manager1 = new DBManager(); SqlConnection connection = manager1.Connection(); string seletQuery = "select * from Books Order by Name"; SqlCommand selectCmd = new SqlCommand(seletQuery, connection); connection.Open(); SqlDataAdapter myAdapter = new SqlDataAdapter(); myAdapter.SelectCommand = selectCmd; dt = new DataTable(); myAdapter.Fill(dt); BindingSource bSource = new BindingSource(); bSource.DataSource = dt; dataGridView1.DataSource = dt; myAdapter.Update(dt); //return null; } catch (Exception obj) { throw new Exception("Error", obj); } }
private void UpdateDB() { // This is the function to call the method UpdateDB() SqlConnection con = new SqlConnection(); SqlDataAdapter da = new SqlDataAdapter(); DataSet dsl = new DataSet(); dsl = new DataSet(); con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\user\\Desktop\\MyWorkers.mdf;Integrated Security=True;User Instance=True"; string sql = "SELECT*From tblWorkers"; da = new System.Data.SqlClient.SqlDataAdapter(sql, con); da.Fill(dsl, "Workers"); da.Update(dsl, "Workers"); System.Data.SqlClient.SqlCommandBuilder cb; cb = new System.Data.SqlClient.SqlCommandBuilder(da); cb.DataAdapter.Update(dsl.Tables["Workers"]); //MaxRows = MaxRows + 1; inc = MaxRows - 1; DataRow dRow = dsl.Tables["Workers"].Rows[inc]; dRow[0] = txtWorkerID.Text; dRow[1] = txtFirstName.Text; dRow[2] = textBox1.Text; dRow[3] = txtAge.Text; dRow[4] = txtJobTitle.Text; dRow[5] = txtDepartment.Text; dRow[6] = txtSalary.Text; }
protected void FinishButton_Click(object sender, System.EventArgs e) { if (!IsValid) { return; } //if (CommonFunctions.Connection.State == System.Data.ConnectionState.Closed) //CommonFunctions.Connection.Open (); //lock (CommonFunctions.Connection) PropertiesAdapter.Update(PropertiesSet); //get top photo and make thumbnail if not already exist..don't forget to delete thumbnails when delete, names not in db DBConnection obj = new DBConnection(); try { DataTable dt = VADBCommander.PropertyPhotoTopOne(propertyid.ToString()); //create thumbnail for top photo or overwrite if (dt.Rows.Count > 0) { File.Delete("C:\\Inetpub\\wwwroot\\vacations-abroad\\httpdocs\\images\\TH" + dt.Rows[0]["filename"].ToString()); //see if file exists if (!File.Exists("C:\\Inetpub\\wwwroot\\vacations-abroad\\httpdocs\\images\\TH" + dt.Rows[0]["filename"].ToString())) { System.IO.FileStream streamFrom = new System.IO.FileStream("C:\\Inetpub\\wwwroot\\vacations-abroad\\httpdocs\\images\\" + dt.Rows[0]["filename"].ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.FileStream streamTo = new FileStream("C:\\Inetpub\\wwwroot\\vacations-abroad\\httpdocs\\images\\TH" + dt.Rows[0]["filename"].ToString(), FileMode.Create, FileAccess.Write); ResizeImage(streamFrom, streamTo); } } } catch (Exception ex) { lblInfo.Text = ex.Message; } finally { obj.CloseConnection(); } //get top photo and make thumbnail if not already exist..don't forget to delete thumbnails when delete, names not in db if (ifadd) { if (ifauction) { Response.Redirect(CommonFunctions.PrepareURL("MakePayment.aspx?UserID=" + userid.ToString() + "&AuctionID=" + auctionid.ToString(), backlinktext)); } else { Response.Redirect(CommonFunctions.PrepareURL("PublishProperty.aspx?UserID=" + userid.ToString() + "&PropertyID=" + propertyid.ToString(), backlinktext)); } } else if (ifauction) { Response.Redirect(CommonFunctions.PrepareURL("MyAccount.aspx")); } else { Response.Redirect(backlinkurl); } }
private void btnSave_Click(object sender, System.EventArgs e) { if (this.txtID.Text.Trim() == "" || this.txtArea.Text.Trim() == "" || this.txtNum.Text.Trim() == "" || this.txtPrice.Text.Trim() == "") { MessageBox.Show("类型编号、房间面积、床位数量、客房价格不能空"); } else { try { HotelDataSet.客房标准信息Row dr = ds.客房标准信息.New客房标准信息Row(); dr.类型编号 = this.txtID.Text.Trim(); dr.客房类型 = this.txtname.Text.Trim(); dr.房间面积 = decimal.Parse(this.txtArea.Text.Trim()); dr.床位数量 = Int32.Parse(this.txtNum.Text.Trim()); dr.客房价格 = decimal.Parse(this.txtPrice.Text.Trim()); dr.空调 = this.checkBox1.Checked; dr.电视机 = this.checkBox2.Checked; dr.电话 = this.checkBox3.Checked; dr.单独卫生间 = this.checkBox4.Checked; this.ds.客房标准信息.Add客房标准信息Row(dr); da.Update(ds, "客房标准信息"); MessageBox.Show("数据保存成功"); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } }
public void GetAllSelfOrder() { try { connection = manager.Connection(); string query = "Select [Serial No] as SN,[Book Name],[Writer Name],Edition,Type,[Print],Quanitity from Self_Order"; SqlCommand command = new SqlCommand(query, connection); connection.Open(); SqlDataAdapter myAdapter = new SqlDataAdapter(); myAdapter.SelectCommand = command; DataTable dataTable = new DataTable(); myAdapter.Fill(dataTable); BindingSource bsSource = new BindingSource(); bsSource.DataSource = dataTable; dataGridView1.DataSource = dataTable; myAdapter.Update(dataTable); } catch (Exception exception) { MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { connection.Close(); } }
private void btnLaatZien_Click(object sender, RoutedEventArgs e) { SqlConnection sql = new SqlConnection(clStam.Connstr); try { sql.Open(); string query = "select Gebrnr, Vnaam, Tnaam, Anaam from Gebruikers"; SqlCommand createCommand = new SqlCommand(query, sql); createCommand.ExecuteNonQuery(); SqlDataAdapter dataAdp = new SqlDataAdapter(createCommand); DataTable dt = new DataTable("Gebruikers"); dataAdp.Fill(dt); gegevens.ItemsSource = dt.DefaultView; dataAdp.Update(dt); sql.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private static void AtualizarPrecosViaAdapter(SqlConnection conn) { var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * FROM Produto"; using (var da = new SqlDataAdapter(cmd)) { var builder = new SqlCommandBuilder(da); builder.ConflictOption = ConflictOption.CompareRowVersion; da.UpdateCommand = builder.GetUpdateCommand(); DataSet ds = new DataSet(); da.Fill(ds); foreach (DataRow row in ds.Tables[0].Rows) { var preco = double.Parse(row["Preco"].ToString()); preco += 10; row["Preco"] = preco; } da.Update(ds); } }
private void Delete() { // This is the function to call the method delete() SqlConnection con = new SqlConnection(); SqlDataAdapter da = new SqlDataAdapter(); DataSet dsl = new DataSet(); con = new System.Data.SqlClient.SqlConnection(); dsl = new DataSet(); con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\user\\Desktop\\Employee Database\\Employee Database\\MyWorkers.mdf;Integrated Security=True;User Instance=True"; con.Open(); string sql = "SELECT*From tblWorkers"; da = new System.Data.SqlClient.SqlDataAdapter(sql, con); // Fill the dataset with recors da.Fill(dsl, "Workers"); System.Data.SqlClient.SqlCommandBuilder cb; cb = new System.Data.SqlClient.SqlCommandBuilder(da); dsl.Tables["Workers"].Rows[inc].Delete(); MaxRows--; inc = 0; da.Update(dsl, "Workers"); con.Close(); con.Dispose(); }
public void LoadAllBook() { try { DBManager manager = new DBManager(); SqlConnection connection = manager.Connection(); string selectQuery = "SELECT * From Books"; SqlCommand cmd = new SqlCommand(selectQuery, connection); //connection.Open(); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = cmd; dataTable = new DataTable(); adapter.Fill(dataTable); BindingSource binding = new BindingSource(); binding.DataSource = dataTable; dataGridView1.DataSource = dataTable; adapter.Update(dataTable); } catch ( SqlException exception) { MessageBox.Show(exception.Message); } }
protected void Button2_Click(object sender, EventArgs e) { string qq = "Data Source=gz-20150728tajv\\sqlexpress;Initial Catalog=Student1;Integrated Security=True "; SqlConnection Conn = new SqlConnection(qq); SqlDataAdapter da = new SqlDataAdapter(); string SQL = "select * from Hydropower"; da.SelectCommand = new SqlCommand(SQL, Conn); DataSet ds = new DataSet(); da.Fill(ds, "Hydropower"); DataRow dr = ds.Tables["Hydropower"].NewRow(); dr["寝室号"] = TextBox1.Text.ToString(); dr["月份"] = TextBox9.Text.ToString(); dr["度数"] = TextBox2.Text.ToString(); dr["单价"] = TextBox3.Text.ToString(); dr["总金额"] = TextBox4.Text.ToString(); dr["是否交钱"] = TextBox5.Text.ToString(); ds.Tables[0].Rows.Add(dr); SqlCommandBuilder read = new SqlCommandBuilder(da); da.Update(ds, "Hydropower"); GridView1.DataSource = ds; GridView1.DataBind(); }
public int ExecuteNoneQuery() { int result = 0; SqlTransaction tr = null; try { tr = m_Connection.BeginTransaction(); m_Command.Connection = m_Connection; m_Command.Transaction = tr; m_DataAdapter = new SqlDataAdapter(); m_DataAdapter.SelectCommand = m_Command; SqlCommandBuilder builder = new SqlCommandBuilder(m_DataAdapter); result = m_DataAdapter.Update(this); tr.Commit(); } catch (System.Exception ex) { if (tr != null) tr.Rollback(); } return result; }
/// <summary> /// 保存表修改到数据库 /// </summary> /// <returns>保存的行数</returns> public int SaveTable() { int nRet = 0; if (mTableChanged || true) { try { mAdapter = new SqlDataAdapter(mSqlCmd, mConn); SqlCommandBuilder cmd = new SqlCommandBuilder(mAdapter); mAdapter.UpdateCommand = cmd.GetUpdateCommand(); DataTable tbl = mTable.GetChanges(); if (tbl != null && tbl.Rows.Count > 0) { nRet = mAdapter.Update(tbl); } mTable.AcceptChanges(); mTableChanged = false; } catch(Exception ex) { throw ex; } } return nRet; }
private void button1_Click(object sender, EventArgs e) { try { DBManager manager = new DBManager(); SqlConnection connection = manager.Connection(); string selectQuery = "select * from Income"; SqlCommand cmd = new SqlCommand(selectQuery, connection); connection.Open(); SqlDataAdapter myAdapter = new SqlDataAdapter(); myAdapter.SelectCommand = cmd; dataTable = new DataTable(); myAdapter.Fill(dataTable); BindingSource bSource = new BindingSource(); bSource.DataSource = dataTable; dataGridView1.DataSource = bSource; myAdapter.Update(dataTable); } catch (SqlException ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void btnLoad_Click(object sender, EventArgs e) { connection = new SqlConnection(); connection.ConnectionString = DBHelper.ConnectionString(); connection.Open(); command = new SqlCommand(); command.Connection = connection; command.CommandText = "select * from newCoustomer_db"; try { SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = command; dbdataset = new DataTable(); da.Fill(dbdataset); BindingSource bsource = new BindingSource(); bsource.DataSource = new BindingSource(); bsource.DataSource = dbdataset; dataGridView1.DataSource = bsource; da.Update(dbdataset); } catch(Exception ex) { MessageBox.Show(ex.Message); } }
public static int ExecuteSQLUpdate(DataTable dt, string sqlsr) { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ISBEPI_DEV"].ToString()); SqlDataAdapter da = new SqlDataAdapter(sqlsr,conn); using (new SqlCommandBuilder(da)) { try { DataTable updt = new DataTable(); da.Fill(updt); updt.Rows[0]["PD_EDUCATIONANDEXPERIENCE_Q12_1"] = dt.Rows[0]["PD_EDUCATIONANDEXPERIENCE_Q12_1"].ToString(); updt.Rows[0]["PD_EDUCATIONANDEXPERIENCE_Q12_2"] = dt.Rows[0]["PD_EDUCATIONANDEXPERIENCE_Q12_2"].ToString(); updt.Rows[0]["PD_EDUCATIONANDEXPERIENCE_Q12_3"] = dt.Rows[0]["PD_EDUCATIONANDEXPERIENCE_Q12_3"].ToString(); updt.Rows[0]["PD_EDUCATION_Q13"] = dt.Rows[0]["PD_EDUCATION_Q13"].ToString(); updt.Rows[0]["PD_EDUCATION_Q14"] = dt.Rows[0]["PD_EDUCATION_Q14"].ToString(); updt.Rows[0]["PD_EDUCATION_Q15"] = dt.Rows[0]["PD_EDUCATION_Q15"].ToString(); updt.Rows[0]["PD_EDUCATION_Q16"] = dt.Rows[0]["PD_EDUCATION_Q16"].ToString(); updt.Rows[0]["PD_EDUCATION_Q17"] = dt.Rows[0]["PD_EDUCATION_Q17"].ToString(); updt.Rows[0]["PD_EDUCATION_Q17"] = dt.Rows[0]["PD_EDUCATION_Q17"].ToString(); conn.Open(); int message = da.Update(updt); conn.Close(); return message; } catch { return 0; } } }
protected void btnUpdate_Click(object sender, EventArgs e) { string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; using (SqlConnection con = new SqlConnection(cs)) { SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand((string)ViewState["SQL_QUERY"], con); SqlCommandBuilder builder = new SqlCommandBuilder(); builder.DataAdapter = da; DataSet ds = (DataSet)ViewState["DATASET"]; if (ds.Tables["Students"].Rows.Count > 0) { DataRow dr = ds.Tables["Students"].Rows[0]; dr["Name"] = txtStudentName.Text; dr["Gender"] = ddlGender.SelectedValue; dr["TotalMarks"] = txtTotalMarks.Text; } //this line not working saying command error. int rowsupdated = da.Update(ds, "Students"); if(rowsupdated > 0) { lblStatus.ForeColor = System.Drawing.Color.Green; lblStatus.Text = rowsupdated.ToString() + "rows(s) updated"; } else { lblStatus.ForeColor = System.Drawing.Color.Red; lblStatus.Text = " No rows(s) updated"; } } }
protected void Submit_Click(object sender, EventArgs e) { string strConn = WebConfigurationManager.ConnectionStrings["dmtucaoConnectionString"].ConnectionString; SqlConnection con = new SqlConnection(strConn); con.Open(); SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM [User] WHERE [username]='" + Session["UserName"] + "'", con); SqlCommandBuilder scb = new SqlCommandBuilder(da); DataSet ds = new DataSet(); da.Fill(ds, "user"); if (ds.Tables["user"].Rows.Count > 0) { ds.Tables["user"].Rows[0]["face"] = FaceUrl.Text; ds.Tables["user"].Rows[0]["sex"] = Sex.SelectedIndex; ds.Tables["user"].Rows[0]["email"] = Email.Text; ds.Tables["user"].Rows[0]["qq"] = QQ.Text; ds.Tables["user"].Rows[0]["telephone"] = PhoneNumber.Text; ds.Tables["user"].Rows[0]["birthday"] = Birthday.Text; ds.Tables["user"].Rows[0]["introduction"] = Introduction.Text; if (da.Update(ds, "user") == 1) ClientScript.RegisterStartupScript(GetType(), "成功", "<script>alert('修改成功');location.reload();</script>"); } con.Close(); con = null; return; }
/*USED IN THE USER CREATION PROCESS * FUNCTION :This method create a new user in the DB * RETURN :TRUE if the user is created, FALSE orthewise * MORE :Before calling this method, the "login" of the new user * will be previously validate with the method "VALIDATELOGIN(string login) above **/ public bool CreateNewUserCAD(UserClass user) { bool updated = false; DataSet bdvirtual = new DataSet(); try { SqlDataAdapter da = new SqlDataAdapter("select *from UserTable", c); da.Fill(bdvirtual, "UserTable"); DataTable tabla = new DataTable(); tabla = bdvirtual.Tables["UserTable"]; DataRow nuevaFila = tabla.NewRow(); nuevaFila[0] = 2; nuevaFila[1] = user.FirstName; nuevaFila[2] = user.LastName; nuevaFila[3] = user.DateOfBirth; nuevaFila[4] = user.UserName; nuevaFila[5] = user.Password; nuevaFila[6] = user.Email; nuevaFila[7] = user.Country; tabla.Rows.Add(nuevaFila); SqlCommandBuilder cbuilder = new SqlCommandBuilder(da); da.Update(bdvirtual, "UserTable"); updated = true; } catch (SqlException exp){updated = false;} finally{c.Close();} return updated; }
public int DeleteSocialSheetDO(DataSet dataSet) { SqlConnection conn = WorkingContext.GetConnection(); // Build the command SqlCommand sqlCommand = new SqlCommand("DeleteSocialSheet", conn); sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.Add(WorkingContext.CreateParam("@PeriodID", SqlDbType.Int, "PeriodID")); sqlCommand.Parameters.Add(WorkingContext.CreateParam("@RegRestID", SqlDbType.Int, "RegRestID")); sqlCommand.Parameters.Add(WorkingContext.CreateParam("@EmployeeID", SqlDbType.Int, "EmployeeID")); //sqlCommand.Parameters.Add(WorkingContext.CreateParam("@Month", SqlDbType.Int, "Month")); SqlDataAdapter dataAdapter = new SqlDataAdapter(); dataAdapter.DeleteCommand = sqlCommand; try { conn.Open(); return dataAdapter.Update(dataSet.Tables[0]); } catch(Exception oException) { MessageBox.Show(oException.ToString()); return 0; } finally { conn.Dispose(); conn.Close(); } }
/// <summary> /// Xóa một người dùng khỏi hệ thống /// </summary> /// <param name="dataSet"></param> /// <returns></returns> public int DeletePayrollItem(DataSet dataSet) { conn = WorkingContext.GetConnection(); sqlCommand = new SqlCommand("DeletePayrollItem", conn); sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.Add(new SqlParameter("@PayrollItemID", SqlDbType.VarChar, 20, "PayrollItemID")); dataAdapter = new SqlDataAdapter(); dataAdapter.DeleteCommand = sqlCommand; try { conn.Open(); return dataAdapter.Update(dataSet.Tables[0]); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return 0; } finally { conn.Close(); } }
private void ultraButton1_Click(object sender, EventArgs e) { DataSet ds = new DataSet("SottoConti"); SqlConnection conn = new SqlConnection("Data Source=sfera.nadirweb.it;Database=Sfera;User ID=sa;Password=fanREA68;"); SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM SottoConti ORDER BY CodiceConto", conn); SqlCommandBuilder sqlCmb = new SqlCommandBuilder(da); da.Fill(ds, "SottoConti"); DataTable tbSottoConti = ds.Tables[0]; int oldCodiceConto = (int)tbSottoConti.Rows[0]["CodiceConto"]; int index = 0; foreach (DataRow dr in tbSottoConti.Rows) { if (dr["CodiceSottoConto"] == DBNull.Value || dr["CodiceSottoConto"].ToString() == string.Empty) { if ((int)dr["CodiceConto"] != oldCodiceConto) { index = 0; oldCodiceConto = (int)dr["CodiceConto"]; } index = index + 1; dr["CodiceSottoConto"] = index.ToString().PadLeft(3,'0'); } } da.Update(ds, "SottoConti"); }
private void DataGridViewShow() { string sqltxt = "select * from sys_meta_info where tablename = '" + tablename_comboBox.Text + "'"; m_adp = new SqlDataAdapter(sqltxt, m_conn); System.Data.DataSet DS = new System.Data.DataSet(); m_adp.Fill(DS); m_dic_meta_info_Table = DS.Tables[0]; if (m_dic_meta_info_Table.Rows.Count == 0) { if (DialogResult.Yes == MessageBox.Show("没有任何关于" + tablename_comboBox.Text + "表的相关数据!是否要自动添加所有记录", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1)) { for (int index = 0; index < fieldname_comboBox.Items.Count; index++) { System.Data.DataRow dataRow; dataRow = m_dic_meta_info_Table.NewRow(); dataRow.BeginEdit(); dataRow["tablename"] = (tablename_comboBox.Text.Trim() == "" ? null : tablename_comboBox.Text.Trim()); dataRow["fieldname"] = fieldname_comboBox.Items[index].ToString().Trim(); dataRow["fieldcnname"] = null; dataRow["editortype"] = "text"; dataRow["catname"] = null; dataRow["orderno"] = "0"; dataRow["description"] = null; dataRow["listtable"] = null; dataRow["listcondition"] = null; dataRow["keyfield"] = null; dataRow["listfield"] = null; dataRow["listvalues"] = null; dataRow["visible"] = 1; dataRow["readonly"] = 0; m_dic_meta_info_Table.Rows.Add(dataRow); dataRow.EndEdit(); } try { //使用SqlCommandBuilder 对像填充SqlDataAdapter 的InsertCommand、DeleteCommand、UpdateCommand对像 SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(m_adp); m_adp.UpdateCommand = cmdBuilder.GetUpdateCommand(); int val = m_adp.Update(m_dic_meta_info_Table); m_dic_meta_info_Table.AcceptChanges(); } catch (Exception ex) { // m_dic_meta_info_Table.Rows[m_dic_meta_info_Table.Rows.Count - 1].Delete(); MessageBox.Show(ex.Message); } } } //DataColumn[] primarKey = new DataColumn[1]; //primarKey[0] = m_dic_meta_info_Table.Columns["fieldname"]; //m_dic_meta_info_Table.PrimaryKey = primarKey; dataGridView1.DataSource = m_dic_meta_info_Table; }
private void btnSave_Click(object sender, System.EventArgs e) { try { bmb.EndCurrentEdit(); da.Update(ds, "管理员"); this.ds.Clear(); da.Fill(this.ds, "管理员"); bmb = this.BindingContext[ds, "管理员"]; this.label6.Text = "当前记录:" + (this.dataGrid1.CurrentRowIndex + 1); this.label7.Text = "记录数:" + this.bmb.Count; MessageBox.Show("数据修改成功"); } catch (Exception ex) { MessageBox.Show("修改失败:" + ex.Message.ToString()); } }
private void btnUpdate_Click(object sender, System.EventArgs e) { try { sqlDataAdapter1.Update(dataSet1.Tables["autores"]); } catch (Exception ex) { if (dataSet1.HasErrors) { foreach (DataTable dt in dataSet1.Tables) { if (dt.HasErrors) { foreach (DataRow dr in dt.Rows) { if (dr.HasErrors) { foreach (DataColumn col in dr.GetColumnsInError()) { MessageBox.Show(string.Format("La columna {0} presento el siguiente error: {1}", col.ColumnName, dr.GetColumnError(col))); } MessageBox.Show(dr.RowError); // DataSet ds2 = new DataSet(); SqlDataAdapter da2 = new SqlDataAdapter("select au_lname from authors where au_id='" + dr["au_id"] + "'", sqlConnection1); da2.Fill(ds2); //Corrijo el valor y vuelvo a aplicar //dr["au_lname", DataRowVersion.Original] = ds2.Tables[0].Rows[0]["au_lname"]; dr.BeginEdit(); dr["au_lname", DataRowVersion.Original] = ds2.Tables[0].Rows[0]["au_lname"]; dr.EndEdit(); sqlDataAdapter1.Update(dataSet1); } } } } } } }
protected void StateRename_Click(object sender, System.EventArgs e) { if (StateName.Text.Length < 1) { return; } foreach (DataRow datarow in StateProvincesSet.Tables["StateProvinces"].Rows) { if (datarow.RowState != DataRowState.Deleted) { if ((int)datarow["ID"] == Convert.ToInt32(StateList.SelectedValue)) { datarow["StateProvince"] = StateName.Text; break; } } } //lock (CommonFunctions.Connection) StateProvincesAdapter.Update(StateProvincesSet); Finish(); List <SqlParameter> param = new List <SqlParameter>(); param.Add(new SqlParameter("@country", CountryList.Text)); param.Add(new SqlParameter("@state", StateName.Text)); param.Add(new SqlParameter("@city", CityList.Text)); param.Add(new SqlParameter("@ocount", CountryList.Text)); param.Add(new SqlParameter("@ostate", StateList.Text)); param.Add(new SqlParameter("@ocity", CityList.Text)); BookDBProvider.getDataSet("uspUpdateLatLong", param); }
/// <summary> /// 保存数据表所做的更改(不带事务) /// </summary> /// <param name="ConnStr">连接字符串</param> /// <param name="strSQL">SQL查询语句</param> /// <param name="dt">DataGridView的DataSource的DataTable</param> public static void SaveChanges(string ConnStr, string strSQL, SD.DataTable dt) { //this.Validate(); try { using (sqlconn = new SDC.SqlConnection(ConnStr)) { sqlconn.Open(); using (sqlcmd = new SDC.SqlCommand(strSQL, sqlconn)) { using (sqladp = new SDC.SqlDataAdapter(sqlcmd)) { using (sqlcmdbd = new SDC.SqlCommandBuilder(sqladp)) { sqlcmdbd.ConflictOption = SD.ConflictOption.CompareAllSearchableValues; sqladp.InsertCommand = sqlcmdbd.GetInsertCommand(); sqladp.UpdateCommand = sqlcmdbd.GetUpdateCommand(); sqladp.DeleteCommand = sqlcmdbd.GetDeleteCommand(); sqladp.Update(dt); } } } } } catch (SDC.SqlException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { if (sqlconn != null) { if (sqlconn.State != SD.ConnectionState.Closed) { sqlconn.Close(); } sqlconn.Dispose(); } } }
public void MyCmdSalir_Click() { try { SqlCommandBuilder com = new SqlCommandBuilder(_DA); _DA.Update(ReymiTable.Table); MessageBox.Show("Done..."); this.View.Close(); } catch (Exception ex) { MethodBase site = ex.TargetSite; MessageBox.Show(ex.Message, site.Name, MessageBoxButton.OK, MessageBoxImage.Error); } }
protected void RegionRename_Click(object sender, System.EventArgs e) { if (RegionName.Text.Length < 1) { return; } foreach (DataRow datarow in RegionsSet.Tables["Regions"].Rows) { if (datarow.RowState != DataRowState.Deleted) { if ((int)datarow["ID"] == Convert.ToInt32(RegionList.SelectedValue)) { datarow["Region"] = RegionName.Text; break; } } } //lock (CommonFunctions.Connection) RegionsAdapter.Update(RegionsSet); Finish(); }
public void UpdateDataSource(DataSetReader Changerows) { try { conn.Open(); da.Update(Changerows); } catch (System.Exception E) { this.ErrorHandle(E); } finally { conn.Close(); } }
} // end updateAgent private void updateSpecialties() { //find all specialties associated with this agent try { string query; DataSet dsTemp = new DataSet(); DataRow tempRow; int agentID = cboAgent.SelectedIndex; //find all current rows for this agent query = "SELECT * FROM Agent_Specialty "; query += "WHERE AgentID = "; query += agentID.ToString(); //delete rows from database adAgentSpec.SelectCommand.CommandText = query; adAgentSpec.Fill(dsSpy, "Agent_Specialty"); foreach (DataRow myRow in dsSpy.Agent_Specialty.Rows) { myRow.Delete(); } // end foreach //adAgentSpec.Update(dsSpy, "Agent_Specialty"); //find the largest id query = "SELECT MAX(Agent_SpecialtyID) FROM Agent_Specialty"; adAgentSpec.SelectCommand.CommandText = query; dsTemp = new DataSet(); adAgentSpec.Fill(dsTemp, "results"); tempRow = dsTemp.Tables["results"].Rows[0]; int largestID = Convert.ToInt32(tempRow[0]); int newID = largestID + 1; //add rows foreach (int specID in clbSpec.CheckedIndices) { dsSpy.Agent_Specialty.AddAgent_SpecialtyRow( newID, agentID, specID); newID++; } // end foreach dsSpy.AcceptChanges(); adAgentSpec.Update(dsSpy, "Agent_Specialty"); dgTemp.SetDataBinding(dsSpy, "Agent_Specialty"); } catch (Exception exc) { MessageBox.Show(exc.Message); } // end try } // end updateSpecialties();
protected void CityRename_Click(object sender, System.EventArgs e) { if (CityName.Text.Length < 1) { return; } LatLongInfo latinfo = MainHelper.getCityLocation(CityName.Text, StateList.SelectedItem.Text, CountryList.SelectedItem.Text); if (latinfo.status == 0) //Fail to get location info { error_msg = String.Format("Fail to get {0} location.", NewCity.Text); } else if (latinfo.status == 1) //Fail to verify the address { error_msg = String.Format("Fail to verify the location of {0}.", NewCity.Text); } else //Success to get the latitude and longitude { try { //Update foreach (DataRow datarow in CitiesSet.Tables["Cities"].Rows) { if (datarow.RowState != DataRowState.Deleted) { if ((int)datarow["ID"] == Convert.ToInt32(CityList.SelectedValue)) { datarow["City"] = CityName.Text; break; } } } //lock (CommonFunctions.Connection) CitiesAdapter.Update(CitiesSet); List <SqlParameter> param = new List <SqlParameter>(); param.Add(new SqlParameter("@stateid", StateList.SelectedValue)); param.Add(new SqlParameter("@city", CityName.Text)); param.Add(new SqlParameter("@lat", latinfo.latitude)); param.Add(new SqlParameter("@lng", latinfo.longitude)); BookDBProvider.getDataSet("uspAddLatLong", param); Finish(); } catch { error_msg = "Something is wrong."; } } }
private static List <string> UpdateIsVisibleAndRetrievePath(string sqlcmds) { List <string> path = new List <string>(); using (SqlConnection conn = new SqlConnection(configData.strconn)) { conn.Open(); try { SqlCommand selectcmd = new SqlCommand(sqlcmds, conn); SqlCommand updatecmd = new SqlCommand("sp_CrashLinkUpdate", conn); updatecmd.CommandType = CommandType.StoredProcedure; updatecmd.Parameters.Add(new SqlParameter("@Isvisible", SqlDbType.Bit, 0, "Isvisible")); //updatecmd.Parameters.Add(new SqlParameter("@CrashLink", SqlDbType.VarChar, 800, "CrashLink")); updatecmd.Parameters.Add(new SqlParameter("@CrashLink_id", SqlDbType.BigInt, 0, "CrashLink_id")); updatecmd.UpdatedRowSource = UpdateRowSource.None; System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(); adapter.SelectCommand = selectcmd; adapter.UpdateCommand = updatecmd; DataSet ds = new DataSet(); adapter.Fill(ds, "tblCrashLink"); foreach (DataRow row in ds.Tables["tblCrashLink"].Rows) { path.Add(Convert.ToString(row["CrashLink"])); row["IsVisible"] = 0; //row["CrashLink"] = ""; } adapter.Update(ds, "tblCrashLink"); //update DB to make the modification take affect } catch (SqlException ex) { string str = ex.Message; Trace.WriteLine("When query or update table tblCrashLink, exception occurs: " + str); } } return(path); }
public void Change(DataTable tablechange) { if (string.IsNullOrWhiteSpace(tablechange.TableName)) { throw new Exception("ChangeSQL tablename error"); } SqlDataReader read = null; //SqlCommand cmd = null; SqlDataAdapter adapter = null; try { this.sqlMutex.WaitOne(); if (conn == null) { this.Open(); } adapter = new System.Data.SqlClient.SqlDataAdapter(); adapter.SelectCommand = new System.Data.SqlClient.SqlCommand("SELECT * FROM " + tablechange.TableName, this.conn); System.Data.SqlClient.SqlCommandBuilder cmdBldr = new System.Data.SqlClient.SqlCommandBuilder(adapter); adapter.UpdateCommand = cmdBldr.GetUpdateCommand(); //System.Data.SqlClient.SqlCommand cmd = cmdBldr.GetUpdateCommand(); //Console.WriteLine(cmd.ToString()); adapter.Update(tablechange); } finally { try { adapter.Dispose(); } catch { } if (transac == null) { this.Close(); } this.sqlMutex.ReleaseMutex(); } }
private void btnSave_Click(object sender, System.EventArgs e) { if (this.txtBillID.Text.Trim() == "" || this.txtInID.Text.Trim() == "" || this.txtRoomID.Text.Trim() == "" || this.txtPrice.Text.Trim() == "" || this.txtMoney.Text.Trim() == "" || this.txtDiscount.Text.Trim() == "") { MessageBox.Show("帐单编号、入住单号、客房编号、客房价格、消费金额、折扣不能为空"); } else { try { HotelDataSet.帐单明细Row dr = ds.帐单明细.New帐单明细Row(); dr.帐单编号 = this.txtBillID.Text.Trim(); dr.入住单号 = this.txtInID.Text.Trim(); dr.客房编号 = this.txtRoomID.Text.Trim(); dr.客房类型 = this.txtType.Text.Trim(); dr.客房位置 = this.txtPosition.Text.Trim(); dr.客房价格 = decimal.Parse(this.txtPrice.Text.Trim()); dr.顾客姓名 = this.txtName.Text.Trim(); dr.身份证 = this.txtIDCard.Text.Trim(); dr.消费内容 = this.txtContents.Text.Trim(); dr.消费金额 = decimal.Parse(this.txtMoney.Text.Trim()); dr.入住时间 = this.dtArrTime.Value; dr.折扣 = float.Parse(this.txtDiscount.Text.Trim()); dr.结算日期 = this.dtAccountTime.Value; dr.备注 = this.txtRemarks.Text.Trim(); this.ds.帐单明细.Add帐单明细Row(dr); da.Update(ds, "帐单明细"); conn.Open(); this.sqlCommand1.Parameters["@帐单编号"].Value = this.txtBillID.Text.Trim(); this.sqlCommand1.ExecuteNonQuery(); conn.Close(); MessageBox.Show("数据保存成功"); } catch { MessageBox.Show("输入有误"); } } }
private void btnSave_Click(object sender, System.EventArgs e) { if (this.txtID.Text.Trim() == "" || this.txtName.Text.Trim() == "" || this.txtPwd.Text.Trim() == "" || this.txtSection.Text.Trim() == "" || this.txtPost.Text.Trim() == "" || this.txtGrade.Text.Trim() == "" || this.txtPower.Text.Trim() == "") { MessageBox.Show("用户所有信息都不能空"); } else { HotelDataSet.管理员Row dr = this.ds.管理员.New管理员Row(); dr.编号 = this.txtID.Text.Trim(); dr.姓名 = this.txtName.Text.Trim(); dr.密码 = this.txtPwd.Text.Trim(); dr.部门 = this.txtSection.Text.Trim(); dr.职位 = this.txtPost.Text.Trim(); dr.等级 = this.txtGrade.Text.Trim(); dr.权限 = this.txtPower.Text.Trim(); ds.管理员.Add管理员Row(dr); da.Update(ds, "管理员"); MessageBox.Show("数据保存成功"); } }
} // end btnUpdate private void updateAgent() { //updates the agent table DataRow agentRow; int agentID = cboAgent.SelectedIndex; int assignID = lstAssign.SelectedIndex; agentRow = dsSpy.Agents.Rows[agentID]; //Change code name if new name is in text field if (txtCodeName.Text != "") { agentRow["CodeName"] = txtCodeName.Text; txtCodeName.Text = ""; } // end if //change assignment based on lstAssign agentRow["AssignmentID"] = assignID; //update the agent in the main database adAgents.Update(dsSpy, "Agents"); lstAssign.SelectedIndex = assignID; } // end updateAgent
//protected System.Data.SqlClient.SqlConnection Connection; protected void Page_Load(object sender, System.EventArgs e) { System.Data.SqlClient.SqlCommandBuilder builder = new System.Data.SqlClient.SqlCommandBuilder(PhotosAdapter); object auctionidresult = null; using (SqlConnection connection = CommonFunctions.GetConnection()) { connection.Open(); SqlCommand GetAuctionID = new SqlCommand("SELECT ID FROM Auctions WHERE PropertyID = @PropertyID", connection); GetAuctionID.Parameters.Add("@PropertyID", SqlDbType.Int); GetAuctionID.Parameters["@PropertyID"].Value = propertyid; //string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; //CommonFunctions.Connection.ConnectionString = connectionstring; //CommonFunctions.Connection.Open (); auctionidresult = GetAuctionID.ExecuteScalar(); connection.Close(); } bool ifauction = (auctionidresult is int); if (ifauction) { Response.Redirect(CommonFunctions.PrepareURL("InternalError.aspx")); } if (Request.Params["PhotoID"] != null) { photoid = Convert.ToInt32(Request.Params["PhotoID"]); PhotosAdapter.SelectCommand.Parameters["@PhotoID"].Value = photoid; if (CommonFunctions.SyncFill(PhotosAdapter, PhotosSet) > 0) { propertyid = (int)PhotosSet.Tables["PropertyPhotos"].Rows[0]["PropertyID"]; PropertiesAdapter.SelectCommand.Parameters["@PropertyID"].Value = propertyid; if (CommonFunctions.SyncFill(PropertiesAdapter, PropertiesSet) > 0) { int uid = (int)PropertiesSet.Tables["Properties"].Rows[0]["UserID"]; if ((uid == AuthenticationManager.UserID) || (AuthenticationManager.IfAdmin)) { if (System.IO.File.Exists(Request.PhysicalApplicationPath + System.Configuration.ConfigurationManager.AppSettings["ImagesSubfolderPath"] + PhotosSet.Tables["PropertyPhotos"].Rows[0]["FileName"])) { System.IO.File.Delete(Request.PhysicalApplicationPath + System.Configuration.ConfigurationManager.AppSettings["ImagesSubfolderPath"] + PhotosSet.Tables["PropertyPhotos"].Rows[0]["FileName"]); } PhotosSet.Tables["PropertyPhotos"].Rows[0].Delete(); //lock (CommonFunctions.Connection) PhotosAdapter.Update(PhotosSet); } } } } Response.Redirect(backlinkurl); }
private void Bakiyeekle(string Tipi, int cID, decimal tutar = 0, string parabirimi = "TL") { using (SqlConnection conp = new SqlConnection(AyarMetot.conString)) { conp.Open(); using (SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter("select Top 1 * from CASH_paY", conp)) { using (SqlCommandBuilder cb = new SqlCommandBuilder(da)) { DataSet ds1 = new DataSet(); da.Fill(ds1, "CASH_paY"); DataRow dt = ds1.Tables["CASH_paY"].NewRow(); dt["IslemTipi"] = Tipi; dt["IslemNo"] = cID.ToString() + Tipi; try { using (SqlConnection conn = new SqlConnection(AyarMetot.conString)) { conn.Open(); using (SqlCommand cu = new SqlCommand("SELECT MAx(ID)+1 FROM CASH_PAY", conn)) { if (cu.ExecuteScalar() != DBNull.Value) { dt["IslemNo"] = "CB" + cu.ExecuteScalar().ToString(); } else { dt["IslemNo"] = "CB1"; } } } } catch { } dt["IslemTarih"] = DateTime.Now.Date; dt["CariID"] = cID; dt["PersonelID"] = AyarMetot.PersonelID; dt["KasaID"] = -1; dt["BankaID"] = -1; dt["KrediKartiID"] = -1; dt["TaksitSayisi"] = -1; dt["OzelKodID"] = -1; dt["Aciklama"] = "Cari Bakiye Açılışı Yapıldı"; dt["ParaBirimi"] = parabirimi; if (parabirimi == "") { dt["ParaBirimi"] = "TL"; } dt["Tutar"] = tutar; dt["gTutar"] = 0; dt["gParaBirimi"] = ""; dt["aTutar"] = 0; dt["aParaBirimi"] = ""; dt["exRate"] = 1; dt["gonderenID"] = -1; dt["gonderenType"] = ""; dt["alanID"] = -1; dt["alanType"] = ""; dt["Donem"] = AyarMetot.Donem; dt["AlanCariID"] = -1; dt["HavaleMasrafID"] = -1; dt["AdisyonTahsilatID"] = -1; dt["KayitPersonelID"] = AyarMetot.PersonelID; dt["KayitTarih"] = DateTime.Now; dt["FirmaID"] = Convert.ToInt16(Session["FirmaID"].ToString()); string firmaid = Session["FirmaID"].ToString(); string company_code = "SA01" + firmaid.PadLeft(3, '0'); dt["Company_Code"] = company_code; ds1.Tables["CASH_paY"].Rows.Add(dt); da.Update(ds1, "CASH_paY"); } } } }
private void toolStripButton1_Click(object sender, EventArgs e) { int count = 0; Guid[] warehouseZonesIds = new Guid[] { }; if (this.comboBox1.SelectedIndex != -1) { warehouseZonesIds = new Guid[] { Guid.Parse(comboBox1.SelectedValue.ToString()) }; } string msg = String.Empty; bool combine = BatchCombineCheck.Checked; this.dataGridView1.EndEdit(); try { List <object> list = new List <object>(); System.Data.SqlClient.SqlConnection oleConnection = new System.Data.SqlClient.SqlConnection(sql); oleConnection.Open(); DataSet dsSql = new DataSet(); System.Data.SqlClient.SqlDataAdapter oa = new System.Data.SqlClient.SqlDataAdapter("select * from StorageChecking", oleConnection); oa.Fill(dsSql); System.Data.SqlClient.SqlCommandBuilder scb = new System.Data.SqlClient.SqlCommandBuilder(oa); dtn = dsSql.Tables[0]; DateTime date = DateTime.Now; int j = dtn.Rows.Count; if (dataGridView1.Rows.Count == 0) { MessageBox.Show("尚未查询当前库存情况,记录为空!"); return; } var dtnGroup = from i in dtn.AsEnumerable() group i by new { t1 = i.Field <string>("DocumentNum") } into g select new { DocNo = g.FirstOrDefault().Field <string>("DocumentNum").ToString() }; if (dtnGroup != null) { foreach (var item in dtnGroup.ToList()) { if (item.DocNo.Contains(DocNum)) { if (MessageBox.Show("本月已做过盘存操作,如果你需要重新盘存,本月原盘存记录将被清除!", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) { oleConnection = new System.Data.SqlClient.SqlConnection(sql); oleConnection.Open(); System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand(); sqlCommand.Connection = oleConnection; sqlCommand.CommandText = "delete from StorageChecking where DocumentNum LIKE '%" + DocNum + "%'"; sqlCommand.ExecuteNonQuery(); MessageBox.Show("本月旧盘存记录清除完成!"); return; } else { dataGridView1.DataSource = null; return; } } } } foreach (DataGridViewRow r in this.dataGridView1.Rows) { if (Convert.ToDecimal(r.Cells["colRealAmount"].Value) == 0) { count++; r.Cells["colRealAmount"].Style.BackColor = Color.Red; } string pName = r.Cells[0].Value.ToString(); string gg = r.Cells[1].Value.ToString(); string unit = r.Cells[2].Value.ToString(); string pNumber = r.Cells[3].Value.ToString(); string pFactory = r.Cells[4].Value == null ? "无" : r.Cells[4].Value.ToString(); string origin = r.Cells[5].Value == null ? "无" : r.Cells[5].Value.ToString(); string batchNumber = r.Cells[6].Value == null ? "无" : r.Cells[6].Value.ToString(); DateTime pDate = Convert.ToDateTime(r.Cells[7].Value); DateTime validDate = Convert.ToDateTime(r.Cells[8].Value); decimal purchasePrice = Convert.ToDecimal(r.Cells[9].Value); decimal canUsed = Convert.ToDecimal(r.Cells[10].Value); decimal currentIn = Convert.ToDecimal(r.Cells[11].Value); decimal money = Convert.ToDecimal(r.Cells[12].Value); decimal realAmount = r.Cells[13].Value == null? 0m:Convert.ToDecimal(r.Cells[13].Value); decimal dismaindAmount = canUsed - realAmount; DateTime dtime = DateTime.Now; string documentNum = "PCD" + DocNum; string opuser = AppClientContext.CurrentUser.Employee.Name; string wh = r.Cells["Column3"].Value.ToString(); DataRow dr = dtn.NewRow(); dr[0] = j++; dr[1] = pName.ToString(); dr[2] = gg; dr[3] = unit; dr[4] = pNumber; dr[5] = pFactory; dr[6] = origin; dr[7] = batchNumber; dr[8] = pDate; dr[9] = validDate; dr[10] = purchasePrice; dr[11] = canUsed; dr[12] = money; dr[13] = currentIn; dr[14] = realAmount; dr[15] = canUsed - realAmount; dr[16] = dtime; dr[17] = documentNum; dr[18] = opuser; dr[19] = wh; dtn.Rows.Add(dr); } DataTable dty = new DataTable(); if (count > 0) { if (MessageBox.Show("有实盘数据为0,是否继续保存?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) { oa.Update(dtn); dsSql.AcceptChanges(); count = 0; MessageBox.Show("保存成功,损溢数量将自动计算。\n\r请注意:若有药品损溢情况,请申报损溢并审批!"); } else { return; } } else { oa.Update(dtn); dsSql.AcceptChanges(); count = 0; MessageBox.Show("保存成功,损溢数量将自动计算。\n\r请注意:若有药品损溢情况,请申报损溢并审批!"); } oleConnection.Close(); } catch (Exception ex) { MessageBox.Show("操作失败!"); } }
public ActionResult DepoTransferleri(STORE_PROCESS data, string json, string islemtipi) { STORE_PROCESS tk = new STORE_PROCESS(); string KdvDh = "H"; int SiparisID = -1; string Message = "Kayıt Eklendi"; if (data.ID == -1) { tk = data; if (islemtipi == "depogiris") { tk.GonderenDepoID = -1; } else if (islemtipi == "depocikis") { tk.AlanDepoID = -1; } tk.Donem = DateTime.Now.Year.ToString(); tk.KayitPersonelID = Convert.ToInt32(Session["PersonelID"].ToString()); tk.KayitTarih = DateTime.Now; tk.Kur = 1; tk.DolarKur = 1; tk.IslemTarih = Convert.ToDateTime(tk.IslemTarih).ToString("dd.MM.yyyy"); tk.EuroKur = 1; tk.GirisTuru = "Müşteriden Gelen"; tk.TCariID = -1; tk.FirmaID = Convert.ToInt16(Session["FirmaID"].ToString()); string firmaid2 = Session["FirmaID"].ToString(); string company_code = "SA01" + firmaid2.PadLeft(3, '0'); tk.Company_Code = company_code; if (tk.Tutar == null) { tk.Tutar = 0; } db.STORE_PROCESS.Add(tk); db.SaveChanges(); using (SqlConnection conp1 = new SqlConnection(AyarMetot.strcon)) { string srg = @"select top (1) ID FROM STORE_PROCESS Order BY ID Desc"; if (conp1.State == ConnectionState.Closed) { conp1.Open(); } using (SqlCommand sID = new SqlCommand(srg, conp1)) { SiparisID = Convert.ToInt32(sID.ExecuteScalar()); } } } else { tk = db.STORE_PROCESS.Where(x => x.ID == data.ID).FirstOrDefault <STORE_PROCESS>(); if (islemtipi == "depogiris") { tk.GonderenDepoID = -1; } else if (islemtipi == "depocikis") { tk.AlanDepoID = -1; } tk.Donem = DateTime.Now.Year.ToString(); tk.KayitPersonelID = Convert.ToInt32(Session["PersonelID"].ToString()); tk.KayitTarih = DateTime.Now; tk.IslemTarih = Convert.ToDateTime(tk.IslemTarih).ToString("dd.MM.yyyy"); tk.Kur = 1; tk.DolarKur = 1; tk.EuroKur = 1; tk.GirisTuru = "Müşteriden Gelen"; tk.TCariID = -1; tk.FirmaID = Convert.ToInt16(Session["FirmaID"].ToString()); string firmaid2 = Session["FirmaID"].ToString(); string company_code = "SA01" + firmaid2.PadLeft(3, '0'); tk.Company_Code = company_code; db.SaveChanges(); Message = "Kayıt Güncellendi"; } json = "[" + json + "]"; List <STORE_PROCESS_DETAIL> items = JsonConvert.DeserializeObject <List <STORE_PROCESS_DETAIL> >(json); for (int i = 0; i < items.Count; i++) { STORE_PROCESS_DETAIL er = items[i]; decimal Kdv = Convert.ToDecimal(er.KDV); try { if (er.ID.ToString() == "-1" || er.ID.ToString() == "0") { using (SqlConnection con = new SqlConnection(AyarMetot.strcon)) { if (con.State == ConnectionState.Closed) { con.Open(); } using (SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter("select Top 1 * from STORE_PROCESS_DETAIL", con)) { using (SqlCommandBuilder cb = new SqlCommandBuilder(da)) { DataSet ds = new DataSet(); da.Fill(ds, "STORE_PROCESS_DETAIL"); DataRow df = ds.Tables["STORE_PROCESS_DETAIL"].NewRow(); df["DepoIslemID"] = SiparisID; df["IslemTarihi"] = DateTime.Now; df["gDepoID"] = tk.GonderenDepoID; df["aDepoID"] = tk.AlanDepoID; df["personelID"] = tk.personelID; df["urunID"] = er.urunID; df["urunFiyat"] = er.urunFiyat; df["urunMiktar"] = er.urunMiktar; df["urunBirim"] = er.urunBirim; df["paraBirimi"] = tk.paraBirimi; df["Kur"] = tk.Kur; df["Donem"] = DateTime.Now.Year; df["IslemTipi"] = "Depo İşlem"; df["KDV"] = er.KDV; df["Aciklama"] = er.Aciklama; df["GirisTuru"] = tk.GirisTuru; df["TCariID"] = -1; df["TakimID"] = -1; df["KodID"] = -1; df["SiparisIDHFT"] = -1; df["FirmaID"] = tk.FirmaID; df["Company_Code"] = tk.Company_Code; ds.Tables["STORE_PROCESS_DETAIL"].Rows.Add(df); da.Update(ds, "STORE_PROCESS_DETAIL"); } } } } else { using (SqlConnection con = new SqlConnection(AyarMetot.conString)) { if (con.State == ConnectionState.Closed) { con.Open(); } using (SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter( "select * from STORE_PROCESS_DETAIL where ID='" + er.ID + "'", con)) { using (SqlCommandBuilder cb = new SqlCommandBuilder(da)) { DataSet ds = new DataSet(); da.Fill(ds, "STORE_PROCESS_DETAIL"); DataRow[] adf = ds.Tables["STORE_PROCESS_DETAIL"].Select("ID='" + er.ID + "'"); if (adf.Length != 0) { DataRow df = adf[0]; df["DepoIslemID"] = SiparisID; df["IslemTarihi"] = Convert.ToDateTime(data.IslemTarih); df["gDepoID"] = tk.GonderenDepoID; df["aDepoID"] = tk.AlanDepoID; df["personelID"] = tk.personelID; df["urunID"] = er.urunID; df["urunFiyat"] = er.urunFiyat; df["urunMiktar"] = er.urunMiktar; df["urunBirim"] = er.urunBirim; df["paraBirimi"] = tk.paraBirimi; df["Kur"] = tk.Kur; df["Donem"] = DateTime.Now.Year; df["IslemTipi"] = "Depo İşlem"; df["KDV"] = er.KDV; df["Aciklama"] = er.Aciklama; df["GirisTuru"] = tk.GirisTuru; df["TCariID"] = -1; df["TakimID"] = -1; df["KodID"] = -1; df["SiparisIDHFT"] = -1; df["FirmaID"] = tk.FirmaID; df["Company_Code"] = tk.Company_Code; ds.Tables["STORE_PROCESS_DETAIL"].Rows.Add(df); da.Update(ds, "STORE_PROCESS_DETAIL"); } } } } } } catch (Exception E1) { try { System.IO.File.WriteAllText(Path.Combine(@"C:\Users\Alperen\AppData\Local\Sayazilim", "sonuç.xml"), E1.ToString()); } catch { } } } var result = new { sonuc = 1, Message = Message }; return(Json(result, JsonRequestBehavior.AllowGet)); }
public void update() { da.Update(dt); }
protected void SubmitButton_Click(object sender, System.EventArgs e) { string emailtoowner = ""; string emailtosender = ""; string details = ""; string vSubSend = ""; string vSubject = CommonFunctions.GetSiteAddress() + CommonFunctions.PrepareURL(((string)PropertiesFullSet.Tables["Properties"].Rows[0]["Country"]).Replace(" ", "_").ToLower() + "/" + ((string)PropertiesFullSet.Tables["Properties"].Rows[0]["StateProvince"]).Replace(" ", "_").ToLower() + "/" + ((string)PropertiesFullSet.Tables["Properties"].Rows[0]["City"]).Replace(" ", "_").ToLower() + "/" + ((int)PropertiesFullSet.Tables["Properties"].Rows[0]["ID"]).ToString() + "/default.aspx"); if (IfShowContactInfo()) { details = "Inquiry data:<br />" + "Arrival date: " + ArrivalDay.Items[ArrivalDay.SelectedIndex].Value + " " + ArrivalMonth.Items[ArrivalMonth.SelectedIndex].Value + " " + ArrivalYear.Items[ArrivalYear.SelectedIndex].Value + " " + "<br />"; if (HowManyNights.Text.Length > 0) { details += "Length of stay: " + HowManyNights.Text + "<br />"; } if (HowManyAdults.Text.Length > 0) { details += "Number of adults: " + HowManyAdults.Text + "<br />"; } if (HowManyChildren.Text.Length > 0) { details += "Number of children: " + HowManyChildren.Text + "<br />"; } if (ContactTelephone.Text.Length > 0) { details += "Contact telephone: " + ContactTelephone.Text + "<br />"; } if (Telephone.Text.Length > 0) { details += "Telephone: " + Telephone.Text + "<br />"; } if (Telephone2.Text.Length > 0) { details += "Telephone 2: " + Telephone2.Text + "<br />"; } if (Comments.Text.Length > 0) { details += "Comments: " + Comments.Text + "<br />"; } string vSub1 = "Your property \"" + (string)PropertiesFullSet.Tables["Properties"].Rows[0]["Name"] + "\" (" + ((int)PropertiesFullSet.Tables["Properties"].Rows[0]["NumBedrooms"]).ToString() + " Bedroom " + (string)PropertiesFullSet.Tables["Properties"].Rows[0]["Type"] + " in " + (string)PropertiesFullSet.Tables["Properties"].Rows[0]["City"] + " " + (string)PropertiesFullSet.Tables["Properties"].Rows[0]["StateProvince"] + " " + (string)PropertiesFullSet.Tables["Properties"].Rows[0]["Country"] + ")<br />" + //"listed on <a href='" + CommonFunctions.GetSiteAddress() + //"'>" + CommonFunctions.GetSiteName() + "</a>" + "Property URL: <a href='" + vSubject + "'>" + vSubject + "</a><br />" + "Has been inquired about by " + ContactName.Text + " (" + ContactEmail.Text; if (ContactTelephone.Text.Length > 0) { vSub1 += ", contact telephone: " + ContactTelephone.Text; } vSub1 += ").<br />" + details; //FOR SENDER emailtosender = "Thank you for visiting \"" + CommonFunctions.GetSiteName() + "\". We want to provide you with as much information" + " as possible concerning the owner.<br />" + "Their property number is \"" + propertyid.ToString() + "\"<br />" + "Name of Property Owner: " + PropertiesFullSet.Tables["Properties"].Rows[0]["FirstName"].ToString() + " " + PropertiesFullSet.Tables["Properties"].Rows[0]["LastName"].ToString() + "<br />" + ((PropertiesFullSet.Tables["Properties"].Rows[0]["PrimaryTelephone"].ToString().Length > 0) ? "Property Owner Telephone: " + PropertiesFullSet.Tables["Properties"].Rows[0]["PrimaryTelephone"].ToString() + "<br />" : (PropertiesFullSet.Tables["Properties"].Rows[0]["DaytimeTelephone"].ToString().Length > 0) ? "Property Owner Telephone: " + PropertiesFullSet.Tables["Properties"].Rows[0]["DaytimeTelephone"].ToString() + "<br />" : (PropertiesFullSet.Tables["Properties"].Rows[0]["EveningTelephone"].ToString().Length > 0) ? "Property Owner Telephone: " + PropertiesFullSet.Tables["Properties"].Rows[0]["EveningTelephone"].ToString() + "<br />" : (PropertiesFullSet.Tables["Properties"].Rows[0]["MobileTelephone"].ToString().Length > 0) ? "Property Owner Telephone: " + PropertiesFullSet.Tables["Properties"].Rows[0]["MobileTelephone"].ToString() + "<br />" : "") + ((PropertiesFullSet.Tables["Properties"].Rows[0]["TouristBoard"].ToString().Length > 0) ? "They are member of \"Chamber of Commerce\": " + PropertiesFullSet.Tables["Properties"].Rows[0]["TouristBoard"].ToString() + "<br />" : "") + "Below is the email details that were transmitted to the owner:<br /><br />" + details; //FOR SENDER emailtoowner += "Dear " + (string)PropertiesFullSet.Tables["Properties"].Rows[0]["FirstName"] + "!<br /><br />" + "This is an inquiry for your property on <b>Vacations-Abroad.com<b><br/> Send your response <a href='mailto:" + ContactEmail.Text + "?subject=" + vSubject + "'>" + ContactEmail.Text + "</a>.<br/>"; emailtoowner += vSub1; } else { details = "Inquiry data:<br />" + "Arrival date: " + ArrivalDay.Items[ArrivalDay.SelectedIndex].Value + " " + ArrivalMonth.Items[ArrivalMonth.SelectedIndex].Value + " " + ArrivalYear.Items[ArrivalYear.SelectedIndex].Value + " " + "<br />"; if (HowManyNights.Text.Length > 0) { details += "Length of stay: " + HowManyNights.Text + "<br />"; } if (HowManyAdults.Text.Length > 0) { details += "Number of adults: " + HowManyAdults.Text + "<br />"; } if (HowManyChildren.Text.Length > 0) { details += "Number of children: " + HowManyChildren.Text + "<br />"; } if (ContactTelephone.Text.Length > 0) { details += "Contact telephone: " + ContactTelephone.Text + "<br />"; } if (Telephone.Text.Length > 0) { details += "Telephone: " + Telephone.Text + "<br />"; } if (Telephone2.Text.Length > 0) { details += "Telephone 2: " + Telephone2.Text + "<br />"; } if (Comments.Text.Length > 0) { details += "Comments: " + Comments.Text + "<br />"; } emailtoowner = "Dear " + (string)PropertiesFullSet.Tables["Properties"].Rows[0]["FirstName"] + "!<br /><br />" + "<font color=\"red\">Your listing has expired on Vacations-Abroad.com. " + " Our current rate for advertising on our website is: 1 year for $" + System.Configuration.ConfigurationManager.AppSettings["AnnualListingFee"].ToString() + " USD.</font><br />" + "To respond to this inquiry click here: <a href='mailto:" + ContactEmail.Text + "?subject=" + vSubject + "'>" + ContactEmail.Text + "</a>.<br/>" + "You have received an inquiry through the <a href='" + CommonFunctions.GetSiteAddress() + "'>" + CommonFunctions.GetSiteName() + "</a> website for property \"" + (string)PropertiesFullSet.Tables["Properties"].Rows[0]["Name"] + "\" (" + ((int)PropertiesFullSet.Tables["Properties"].Rows[0]["NumBedrooms"]).ToString() + " Bedroom " + (string)PropertiesFullSet.Tables["Properties"].Rows[0]["Type"] + " in " + (string)PropertiesFullSet.Tables["Properties"].Rows[0]["City"] + " " + (string)PropertiesFullSet.Tables["Properties"].Rows[0]["StateProvince"] + " " + (string)PropertiesFullSet.Tables["Properties"].Rows[0]["Country"] + ").<br />" + "This is the URL: <a href='" + vSubject + "'>" + vSubject + "</a><br />" + "Has been inquired about by " + ContactName.Text + " (" + ContactEmail.Text; if (ContactTelephone.Text.Length > 0) { emailtoowner += ", contact telephone: " + ContactTelephone.Text; } emailtoowner += ").<br />" + details + "<br />" + "<font color=\"red\"> We will call this week to discuss.</font>"; /* * emailtosender = "Thank you for visiting \"" + CommonFunctions.GetSiteName () + "\". We want to provide you with as much information" + * " as possible concerning the owner.<br />" + * "Their property number is \"" + propertyid.ToString () + "\"<br />" + * "Name of Property Owner: " + PropertiesFullSet.Tables["Properties"].Rows[0]["FirstName"].ToString () + * " " + PropertiesFullSet.Tables["Properties"].Rows[0]["LastName"].ToString () + "<br />" + * "Below is the email details that were transmitted to the owner:<br /><br />" + * details; */ } emailtoowner = emailtoowner.Replace("\r", "").Replace("\n", Environment.NewLine); emailtosender = emailtosender.Replace("\r", "").Replace("\n", Environment.NewLine); DataRow newrow = EmailsSet.Tables["Emails"].NewRow(); newrow["PropertyID"] = propertyid; newrow["DateTime"] = DateTime.Now; newrow["ContactName"] = First(ContactName.Text, 100); newrow["ContactEmail"] = First(ContactEmail.Text, 100); newrow["ContactTelephone"] = First(ContactTelephone.Text, 100); newrow["ArrivalDate"] = First(ArrivalDay.Items[ArrivalDay.SelectedIndex].Value + " " + ArrivalMonth.Items[ArrivalMonth.SelectedIndex].Value + " " + ArrivalYear.Items[ArrivalYear.SelectedIndex].Value, 100); newrow["Nights"] = First(HowManyNights.Text, 100); newrow["Adults"] = First(HowManyAdults.Text, 100); newrow["Children"] = First(HowManyChildren.Text, 100); newrow["Telephone"] = First(Telephone.Text, 100); newrow["Telephone2"] = First(Telephone2.Text, 100); newrow["Notes"] = First(Comments.Text, 2000); newrow["Email"] = First(emailtoowner, 6000); newrow["IfCustom"] = false; EmailsSet.Tables["Emails"].Rows.Add(newrow); //lock (CommonFunctions.Connection) EmailsAdapter.Update(EmailsSet); System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"); // beginning of actual email sending part //SmtpClient smtpclient = new SmtpClient (ConfigurationManager.AppSettings["SMTPServer"], // int.Parse (ConfigurationManager.AppSettings["SMTPPort"])); SmtpClient smtpclient = new SmtpClient("mail.vacations-abroad.com", 25); //MailMessage message = new MailMessage (IfShowContactInfo () ? // ContactEmail.Text : "ar@" + CommonFunctions.GetDomainName (), (string)PropertiesFullSet.Tables["Properties"].Rows[0]["Email"]); MailMessage message = new MailMessage("*****@*****.**", (string)PropertiesFullSet.Tables["Properties"].Rows[0]["Email"]); message.Subject = CommonFunctions.GetSiteAddress() + CommonFunctions.PrepareURL(((string)PropertiesFullSet.Tables["Properties"].Rows[0]["Country"]).Replace(" ", "_").ToLower() + "/" + ((string)PropertiesFullSet.Tables["Properties"].Rows[0]["StateProvince"]).Replace(" ", "_").ToLower() + "/" + ((string)PropertiesFullSet.Tables["Properties"].Rows[0]["City"]).Replace(" ", "_").ToLower() + "/" + ((int)PropertiesFullSet.Tables["Properties"].Rows[0]["ID"]).ToString() + "/default.aspx"); message.Subject = "Vacations-Abroad.com Reservation Inquiry Property #" + propertyid.ToString(); //use property # in subject emailtoowner = emailtoowner + "<br/><span style=\"font-size:12px\">Linda K. Jenkins</span><br/><span style=\"font-size:10px\">CEO Vacations-Abroad.com<br/>Atlanta, GA<br/>770-687-6889</span> <br/><img align=\"middle\" style=\"height:202px;width:223px;border-width:0px;left:34px\" src=\"http://www.vacations-abroad.com/largelogo.jpg\"/>" + "<span style=\"font-style:italic\">Where you can find unique vacation rentals, boutique hotels, and quaint B&Bs.</span>"; message.Body = emailtoowner; message.IsBodyHtml = true; // message.Headers["Content-Type"] = "text/plain; charset = \"iso-8859-1\""; // Added below to deal with Credential problem of Smarter Mail, on 4/5/08 --LMG smtpclient.Credentials = new System.Net.NetworkCredential("*****@*****.**", System.Configuration.ConfigurationManager.AppSettings["smtpCredential"].ToString()); smtpclient.UseDefaultCredentials = false; if (regex.Match(message.To.ToString()).Success) { try { smtpclient.Send(message); } catch (Exception ex) { } } //TO SENDER if (regex.Match(ContactEmail.Text).Success&& (emailtosender.Length > 0)) { MailMessage message2 = new MailMessage("noreply@" + CommonFunctions.GetDomainName(), ContactEmail.Text); message2.Subject = CommonFunctions.GetSiteAddress() + CommonFunctions.PrepareURL(((string)PropertiesFullSet.Tables["Properties"].Rows[0]["Country"]).Replace(" ", "_").ToLower() + "/" + ((string)PropertiesFullSet.Tables["Properties"].Rows[0]["StateProvince"]).Replace(" ", "_").ToLower() + "/" + ((string)PropertiesFullSet.Tables["Properties"].Rows[0]["City"]).Replace(" ", "_").ToLower() + "/" + ((int)PropertiesFullSet.Tables["Properties"].Rows[0]["ID"]).ToString() + "/default.aspx"); message2.Body = emailtosender; message2.IsBodyHtml = message.IsBodyHtml; //message2.Headers["Content-Type"] = message.Headers["Content-Type"]; message2.From = new MailAddress("*****@*****.**"); smtpclient.Send(message2); } //SUBSCRIBED TO VA if (regex.Match(System.Configuration.ConfigurationManager.AppSettings["InquiryEmail"]).Success) { MailMessage message2 = new MailMessage(IfShowContactInfo() ? ContactEmail.Text : "ar@" + CommonFunctions.GetDomainName(), System.Configuration.ConfigurationManager.AppSettings["InquiryEmail"]); message2.Subject = "Vacations-Abroad.com Reservation Inquiry Property #" + propertyid.ToString(); //use property # in subject message2.Body = emailtoowner; message2.IsBodyHtml = message.IsBodyHtml; //message2.Headers["Content-Type"] = message.Headers["Content-Type"]; message2.From = new MailAddress("*****@*****.**"); smtpclient.Send(message2); } //SUBSCRIBED TO VA if (regex.Match(System.Configuration.ConfigurationManager.AppSettings["InquiryEmail2"]).Success) { MailMessage message2 = new MailMessage(IfShowContactInfo() ? ContactEmail.Text : "ar@" + CommonFunctions.GetDomainName(), System.Configuration.ConfigurationManager.AppSettings["InquiryEmail2"]); message2.Subject = "Reservation Inquiry Property #" + propertyid.ToString(); //use property # in subject message2.Body = emailtoowner; message2.IsBodyHtml = message.IsBodyHtml; //message2.Headers["Content-Type"] = message.Headers["Content-Type"]; message2.From = new MailAddress("*****@*****.**"); smtpclient.Send(message2); } backlinkurl = Session["emailReturnURL"].ToString(); Response.Redirect(backlinkurl); }
public ActionResult Data(Resim file) { if (file.Dosya.ContentLength > 0) { var filenamecmr = Path.GetFileName(file.Dosya.FileName); var kayityeri = Path.Combine(@"C:/FRANCBELGELER", filenamecmr); if (System.IO.File.Exists(kayityeri)) { kayityeri = Path.Combine(@"C:/FRANCBELGELER", filenamecmr); } else { } file.Dosya.SaveAs(kayityeri); DataTable dt = ConvertExcelToDataTable(kayityeri); int EmpID = -1; string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString; try { using (SqlConnection conp = new SqlConnection(strcon)) { if (conp.State == ConnectionState.Closed) { conp.Open(); } using (SqlCommand command = new SqlCommand("SELECT MAX(ID)+1 From Stok", conp)) { EmpID = Convert.ToInt32(command.ExecuteScalar()); } } } catch { } if (EmpID == -1 || EmpID == 0) { EmpID = 1; } try { System.IO.File.WriteAllText(Path.Combine(@"C:\Users\alper\AppData\Local\Sayazilim", "sonuç.xml"), dt.Rows.Count.ToString()); } catch { } int aktarimsay = 0; using (sayazilimEntities db = new sayazilimEntities()) { for (int i = 0; i < dt.Rows.Count; i++) { string Yetkili = ""; bool kayitvar = false; if (kayitvar == false) { using (SqlConnection conp = new SqlConnection(strcon)) { if (conp.State == ConnectionState.Closed) { conp.Open(); } using (SqlDataAdapter daBASVURULAR = new System.Data.SqlClient.SqlDataAdapter("select Top 1 * from Stok", strcon)) { using (SqlCommandBuilder cb = new SqlCommandBuilder(daBASVURULAR)) { try { DateTime Duzenleme = DateTime.Now; string stokkodu = dt.Rows[i]["Kod"].ToString(); short firmaID = Convert.ToInt16(Session["FirmaID"].ToString()); Stok stk = db.Stok.Where(x => x.FirmaID == firmaID && x.StokKodu == stokkodu).FirstOrDefault <Stok>(); Stok st = new Stok(); if (stk != null) { AyarMetot.Siradaki("", "Stok", "StokKodu", Session["FirmaID"].ToString()); st.StokKodu = AyarMetot.GetNumara; } else { st.StokKodu = stokkodu; } st.UrunAdi = dt.Rows[i]["Ad"].ToString(); try { st.Marka = dt.Rows[i]["Marka"].ToString(); } catch { }; try { st.Grubu = dt.Rows[i]["Grubu"].ToString(); } catch { }; try { st.StoktaKalan = Convert.ToInt32(dt.Rows[i]["Ürün Miktarı"].ToString()); } catch { }; try { st.Kategori1 = dt.Rows[i]["Kategori1"].ToString(); } catch { }; try { st.Kategori2 = dt.Rows[i]["Kategori2"].ToString(); } catch { }; try { st.Kategori3 = dt.Rows[i]["Kategori3"].ToString(); } catch { }; try { st.Kategori4 = dt.Rows[i]["Kategori4"].ToString(); } catch { }; try { st.UrunTuru = dt.Rows[i]["Ürün Türü"].ToString(); } catch { }; try { st.AlishFiyat = Convert.ToInt32(dt.Rows[i]["Alış Fiyatı"].ToString()); } catch { }; try { st.SatishFiyat = Convert.ToInt32(dt.Rows[i]["Satış Fiyat"].ToString()); } catch { }; try { st.KDV = Convert.ToInt32(dt.Rows[i]["Kdv"].ToString()); } catch { }; try { st.ParaBirimi = dt.Rows[i]["Satış PB"].ToString(); } catch { }; try { st.Barkod = dt.Rows[i]["Barkod"].ToString(); } catch { }; try { st.F2 = Convert.ToInt32(dt.Rows[i]["F2"].ToString()); } catch { }; try { st.F4 = Convert.ToInt32(dt.Rows[i]["F4"].ToString()); } catch { }; try { st.F5 = Convert.ToInt32(dt.Rows[i]["F5"].ToString()); } catch { }; try { st.F3 = Convert.ToInt32(dt.Rows[i]["F3"].ToString()); } catch { }; try { string depoadi = dt.Rows[i]["Depo Adı"].ToString(); STORE store = db.STORE.Where(x => x.DepoAdi == depoadi && x.FirmaID == firmaID) .FirstOrDefault <STORE>(); st.SdepoID = store.ID; } catch { } st.FirmaID = firmaID; string firmaid = Session["FirmaID"].ToString(); string company_code = "SA01" + firmaid.PadLeft(3, '0'); st.Company_Code = company_code; aktarimsay++; db.Stok.Add(st); db.SaveChanges(); if (stk.StoktaKalan != 0) { int depoIslId = 0; using (SqlConnection con = new SqlConnection(AyarMetot.strcon)) { if (con.State == ConnectionState.Closed) { con.Open(); } using (SqlDataAdapter daDepoIslm = new System.Data.SqlClient.SqlDataAdapter("select Top 1 * from STORE_PROCESS", con)) { using (SqlCommandBuilder cb1 = new SqlCommandBuilder(daDepoIslm)) { DataSet dsDepoIslm = new DataSet(); daDepoIslm.Fill(dsDepoIslm, "STORE_PROCESS"); DataRow dd = dsDepoIslm.Tables["STORE_PROCESS"].NewRow(); dd["IslemKodu"] = stk.ID + "STK"; dd["IslemTarih"] = DateTime.Now.ToString("dd.MM.yyyy"); dd["GonderenDepoID"] = -1; dd["AlanDepoID"] = Session["vDepoID"].ToString(); dd["Aciklama"] = "Stok Açılış Depo Girişi " + DateTime.Now.ToString("dd.MM.yyyy"); dd["Tutar"] = stk.AlishFiyat * stk.StoktaKalan; dd["paraBirimi"] = stk.ParaBirimi; dd["personelID"] = AyarMetot.PersonelID; dd["Donem"] = AyarMetot.Donem; dd["KayitPersonelID"] = AyarMetot.PersonelID; dsDepoIslm.Tables["STORE_PROCESS"].Rows.Add(dd); daDepoIslm.Update(dsDepoIslm, "STORE_PROCESS"); } } } using (SqlConnection conp1 = new SqlConnection(AyarMetot.strcon)) { if (conp1.State == ConnectionState.Closed) { conp1.Open(); } using (SqlCommand sID = new SqlCommand(@"select top (1) ID FROM STORE_PROCESS Order BY ID Desc", conp1)) { depoIslId = Convert.ToInt32(sID.ExecuteScalar()); } } using (SqlConnection con = new SqlConnection(AyarMetot.strcon)) { if (con.State == ConnectionState.Closed) { con.Open(); } using (SqlDataAdapter daSDepoIslm = new System.Data.SqlClient.SqlDataAdapter("select Top 1 * from STORE_PROCESS_DETAIL", con)) { using (SqlCommandBuilder cb1 = new SqlCommandBuilder(daSDepoIslm)) { DataSet dsSDepoIslm = new DataSet(); daSDepoIslm.Fill(dsSDepoIslm, "STORE_PROCESS_DETAIL"); DataRow ds = dsSDepoIslm.Tables["STORE_PROCESS_DETAIL"].NewRow(); ds["DepoIslemID"] = depoIslId; ds["IslemTarihi"] = DateTime.Now.ToString("dd.MM.yyyy"); ds["gDepoID"] = -1; ds["aDepoID"] = Session["vDepoID"].ToString(); ds["urunID"] = stk.ID; ds["urunFiyat"] = stk.AlishFiyat; ds["urunMiktar"] = stk.StoktaKalan; ds["paraBirimi"] = stk.ParaBirimi; ds["variyantID"] = -1; ds["Kur"] = 1; ds["Donem"] = AyarMetot.Donem; ds["personelID"] = AyarMetot.PersonelID; ds["OzelKodID"] = -1; dsSDepoIslm.Tables["STORE_PROCESS_DETAIL"].Rows.Add(ds); daSDepoIslm.Update(dsSDepoIslm, "STORE_PROCESS_DETAIL"); } } } } EmpID++; } catch (Exception E1) { try { System.IO.File.WriteAllText(Path.Combine(@"C:\Users\alper\AppData\Local\Sayazilim", "sonuç.xml"), E1.ToString()); } catch { } } } } } } } } ViewBag.Aktarilan = "Başarılı Aktarılan Stok Sayısı: " + aktarimsay.ToString(); ViewBag.Sayi = "Toplam Stok Sayısı: " + aktarimsay.ToString(); ViewBag.Success = "STOKLAR BAŞARIYLA AKTARILDI"; } //if the code reach here means everthing goes fine and excel data is imported into database return(View()); }