C# (CSharp) Класс System.Data. DataTable Code Examples

C# (CSharp) System.Data.DataTable - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для класса System.Data.DataTable, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
        public static DataTable Sehirler()
        {
            try
            {
                using (baglan = new SqlConnection(ConnectionString))
                {
                    baglan.Open();
                    using (komutver = new SqlCommand())
                    {
                        komutver.Connection = baglan;
                        komutver.CommandText = "sehir_Listele";
                        komutver.CommandType = CommandType.StoredProcedure;
                        adp = new SqlDataAdapter(komutver);
                        dt = new DataTable();
                        adp.Fill(dt);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            return dt;
        }
Пример #2
1
        public static DataTable GetAllCidades(int estado_id)
        {
            DataTable retorno = new DataTable();
            StringBuilder SQL = new StringBuilder();
            SQL.Append(@"SELECT CidadeId, Nome FROM Cidade WHERE EstadoId = @ESTADO_ID");

            try
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Mendes_varejo"].ConnectionString))
                {
                    connection.Open();
                    SqlCommand command = new SqlCommand(SQL.ToString(), connection);
                    command.Parameters.AddWithValue("@ESTADO_ID", estado_id);
                    command.ExecuteNonQuery();
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    adapter.Fill(retorno);
                }
            }
            catch (Exception erro)
            {
                throw erro;
            }

            return retorno;
        }
Пример #3
0
	public void GetReady ()
	{
		dataTable = new DataTable ("itemTable");
		dc1 = new DataColumn ("itemId");
		dc2 = new DataColumn ("itemName");
		dc3 = new DataColumn ("itemPrice");
		dc4 = new DataColumn ("itemCategory");
		
		dataTable.Columns.Add (dc1);
		dataTable.Columns.Add (dc2);
		dataTable.Columns.Add (dc3);
		dataTable.Columns.Add (dc4);
		DataRow dr;
		seed = 123;
		rowCount = 5;
		rndm = new Random (seed);
		for (int i = 1; i <= rowCount; i++) {
			dr = dataTable.NewRow ();
			dr["itemId"] = "item " + i;
			dr["itemName"] = "name " + rndm.Next ();
			dr["itemPrice"] = "Rs. " + (rndm.Next () % 1000);
			dr["itemCategory"] = "Cat " + ((rndm.Next () % 10) + 1);
			dataTable.Rows.Add (dr);
		}
		dataTable.AcceptChanges ();
		dataView = new DataView (dataTable);
		dataView.ListChanged += new ListChangedEventHandler (OnListChanged);
		listChangedArgs = null;
	}
 /// <summary>
 /// Get InvoiceNo Corresponding to Ledger For PurchaseReturn Register
 /// </summary>
 /// <param name="decLedgerId"></param>
 /// <returns></returns>
 public List<DataTable> GetInvoiceNoCorrespondingtoLedgerForPurchaseReturnReport(decimal decLedgerId, decimal decVoucherId)
 {
     List<DataTable> ListObj = new List<DataTable>();
     DataTable dtbl = new DataTable();
     try
     {
         if (sqlcon.State == ConnectionState.Closed)
         {
             sqlcon.Open();
         }
         SqlDataAdapter sqldataadapter = new SqlDataAdapter("GetInvoiceNoCorrespondingtoLedgerForPurchaseReturnReport", sqlcon);
         sqldataadapter.SelectCommand.CommandType = CommandType.StoredProcedure;
         SqlParameter sqlparameter = new SqlParameter();
         sqlparameter = sqldataadapter.SelectCommand.Parameters.Add("@ledgerId", SqlDbType.Decimal);
         sqlparameter.Value = decLedgerId;
         sqlparameter = sqldataadapter.SelectCommand.Parameters.Add("@voucherTypeId", SqlDbType.Decimal);
         sqlparameter.Value = decVoucherId;
         sqldataadapter.Fill(dtbl);
         ListObj.Add(dtbl);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     finally
     {
         sqlcon.Close();
     }
     return ListObj;
 }
Пример #5
0
        private void BindGridView()
        {
            CommonDao<Safezhuan> newmgr = new CommonDao<Safezhuan>();

            DataTable dt = new DataTable();
            dt = newmgr.FindDataTableByCondition("");

            if (dt.Rows.Count == 0)
            {
                dt.Rows.Add(dt.NewRow());
                GridViewEmployee.DataSource = dt;
                GridViewEmployee.DataBind();

                int columnCount = dt.Columns.Count;

                GridViewEmployee.Rows[0].Cells.Clear();

                GridViewEmployee.Rows[0].Cells.Add(new TableCell());

                GridViewEmployee.Rows[0].Cells[0].ColumnSpan = columnCount + 1;

                GridViewEmployee.Rows[0].Cells[0].Text = "没有记录";

                GridViewEmployee.Rows[0].Cells[0].Style.Add("text-align", "center");
            }
            else
            {
                GridViewEmployee.DataSource = dt;
                GridViewEmployee.DataBind();
            }
        }
Пример #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            var datos = new DataTable();
            datos.Columns.Add("Nombre");
            datos.Columns.Add("Activo");

            var row = datos.NewRow();
            row["Nombre"] = "Palma";
            row["Activo"] = "Si";
            datos.Rows.Add(row);

            row = datos.NewRow();
            row["Nombre"] = "Caucho";
            row["Activo"] = "Si";
            datos.Rows.Add(row);

            row = datos.NewRow();
            row["Nombre"] = "Café";
            row["Activo"] = "Si";
            datos.Rows.Add(row);

            ViewState["Datos"] = datos;
            ViewState["ckbActivarFiltro"] = "";
        }
Пример #7
0
 private DataTable GetTiposVenda()
 {
     DataTable dataTable = new DataTable();
     this.con = new SqlConnection(Security.GetCnn());
     string selectCommandText = "";
     if (this._dev != "D")
     {
         selectCommandText = "select tipo_venta_id, descripcion, devolucion from Tipo_venta where devolucion='N'";
     }
     else
     {
         selectCommandText = "select tipo_venta_id, descripcion, devolucion from Tipo_venta where devolucion='S'";
     }
     if ((this.con != null) && (this.con.State == ConnectionState.Open))
     {
         this.con.Close();
     }
     this.con.Open();
     try
     {
         new SqlDataAdapter(selectCommandText, this.con).Fill(dataTable);
         this.con.Close();
     }
     catch (Exception)
     {
     }
     return dataTable;
 }
 public void LoadData()
 {
     GridTable = new DataTable("FalseX2011-07");
     GridTable = MyCL.LoadDataTable("Select knowID, know From CDknow");
     gridControlMain.DataSource = GridTable;
     gridControlMain.RefreshDataSource();
 }
Пример #9
0
        public void Write(DataTable table)
        {
            Log.Debug(String.Format("Writing {0} {1} to database..", table.Rows.Count, "record".Pluralize(table.Rows.Count)));

            // Reopen connection, if it has closed for some reason.
            if (!Adapter.IsConnectionOpen())
            {
                Adapter.OpenConnection();
            }

            // Manage dynamic table creation/management, if requested.
            if (!isInitialized)
            {
                DbTableManager.InitializeTable(Adapter, table, tableInitializationOptions);
                isInitialized = true;
            }

            // Write all rows in table.
            int numRecordsWritten = 0;
            foreach (DataRow row in table.Rows)
            {
                try
                {
                    Adapter.InsertRow(table.TableName, row);
                    numRecordsWritten++;
                }
                catch (DbException) { }
            }
            Log.Debug(String.Format("Finished writing {0} {1}!", numRecordsWritten, "record".Pluralize(numRecordsWritten)));
        }
Пример #10
0
        void ConvertToDataTable()
        {
            ISheet sheet = hssfworkbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

            DataTable dt = new DataTable();
            for (int j = 0; j < 5; j++)
            {
                dt.Columns.Add(Convert.ToChar(((int)'A')+j).ToString());
            }

            while (rows.MoveNext())
            {
                IRow row = (HSSFRow)rows.Current;
                DataRow dr = dt.NewRow();

                for (int i = 0; i < row.LastCellNum; i++)
                {
                    ICell cell = row.GetCell(i);


                    if (cell == null)
                    {
                        dr[i] = null;
                    }
                    else
                    {
                        dr[i] = cell.ToString();
                    }
                }
                dt.Rows.Add(dr);
            }
            dataSet1.Tables.Add(dt);
        }
Пример #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            #region Properties For The Base Class and Check Login
            LoginID = Request.QueryString["LoginID"];
            LoginInfo = CCLib.Login.GetLoginInfo(LoginID);
            Redirect();
            PageTitle = GetPortText(5372, false);
            Section = "portfolio_tool";
            CSS = "student";
            HeadTag = "<STYLE TYPE='TEXT/CSS'><!--.btnDescription {  font: 11px Verdana, Arial, Helvetica, sans-serif; margin: 0px 15px}--></STYLE>";
            BodyTag = " alink='#990000' style='background-image:url(/media/shared/bg_left_bar_grey.gif);background-repeat:repeat-y;' bgcolor='#ffffff' leftmargin=0 link='#003366' text='#000000' topmargin=0 vlink='#003366' marginwidth='0' marginheight='0'";
            LeftBar = "<TABLE WIDTH='100%' BORDER='0' CELLSPACING='0' CELLPADDING='0'><TR VALIGN='TOP' BGCOLOR='#669966'><td background='/media/portfolio_tool/bg_bar_tan_top.gif'><img height=23 src='/media/student_parent/icons/icon_arrow.gif' alt='' width=24><img height=23 src='/media1/" + this.PortType + "/h_h_main" + this.SuffixCode() + ".gif' alt='' width=141>";
            #endregion Properties For The Base Class and Check Login

            #region Initialize Values and Form Execution
            CheckPortSession();

            if (!Page.IsPostBack)
            {
                strSQL = "select c.SectionNameCapital" + SuffixCode() + " Ability,Convert(varchar(10),DBO.fn_ConvertTimeZone(StartTime," + PortInfo["SchoolID"].ToString() + ",1),101) [Test Date], Percentile,CorrectAnswers Correct,TotalQuestions,a.APTestID from AP_SavedTest a join AP_SavedSection b on a.APTestID = b.APTestID join AP_Section c on b.SectionID = c.SectionID where PortfolioID = " + PortInfo["PortfolioID"].ToString() + " and IsActiveStatus = 1 order by b.SectionID";
                dtSummary = CCLib.Common.DataAccess.GetDataTable(strSQL);

                // Prevent user manually change url from browser
                if (dtSummary.Rows.Count == 0)
                    Response.Redirect("AP_Portfolio2.aspx?LoginID=" + LoginID);
                if (dtSummary.Rows.Count > 0 && dtSummary.Rows.Count < 6)
                    Response.Redirect("AP_Portfolio3.aspx?LoginID=" + LoginID);

                //Check if Matchmaker results deleted
                divMM.Visible = false;
                ClientStorage clientStorage = new ClientStorage();
                clientStorage.Retrieve(LoginID);

                if (clientStorage.AspectIndicator < 2)
                {
                    divMM.Visible = true;
                    divLinkMM.Visible = false;
                }
                if (dtSummary.Rows[0]["Percentile"].ToString() == "")
                {
                    UpdateScore();
                    strSQL = "select c.SectionNameCapital" + SuffixCode() + " Ability,Convert(varchar(10),DBO.fn_ConvertTimeZone(StartTime," + PortInfo["SchoolID"].ToString() + ",1),101) [Test Date], Percentile,CorrectAnswers Correct,TotalQuestions,a.APTestID from AP_SavedTest a join AP_SavedSection b on a.APTestID = b.APTestID join AP_Section c on b.SectionID = c.SectionID where PortfolioID = " + PortInfo["PortfolioID"].ToString() + " and SchoolID = " + PortInfo["SchoolID"].ToString() + " and IsActiveStatus = 1 order by b.SectionID";
                    dtSummary = CCLib.Common.DataAccess.GetDataTable(strSQL);
                }
                rptSummary.DataSource = dtSummary;
                rptSummary.DataBind();
                AssignToUserControl();
            }
            #endregion Initialize Values and Form Execution

            #region Properties For The Individual Base Class
            SetCustomJS();
            PortTitle = GetPortText(5372,false);
            SetTitleBar();
            SetLeftButtons();
            PortSubTitle = GetPortText(8804, false);
            SetSubTitleBar();
            SetFooter();
            #endregion Properties For The Individual Base Class
        }
Пример #12
0
	internal static void SetDSInfo(DataTable dsTable) {
		DataRow row = dsTable.NewRow();
		row["TypeName"] = "SMALLINT";
		row["ProviderDbType"] = MySqlDbType.Int16;
		row["ColumnSize"] = 0;
		row["CreateFormat"] = "SMALLINT";
		row["CreateParameters"] = null;
		row["DataType"] = "System.Int16";
		row["IsAutoincrementable"] = true;
		row["IsBestMatch"] = true;
		row["IsCaseSensitive"] = false;
		row["IsFixedLength"] = true;
		row["IsFixedPrecisionScale"] = true;
		row["IsLong"] = false;
		row["IsNullable"] = true;
		row["IsSearchable"] = true;
		row["IsSearchableWithLike"] = false;
		row["IsUnsigned"] = false;
		row["MaximumScale"] = 0;
		row["MinimumScale"] = 0;
		row["IsConcurrencyType"] = DBNull.Value;
		row["IsLiteralsSupported"] = false;
		row["LiteralPrefix"] = null;
		row["LiteralSuffix"] = null;
		row["NativeDataType"] = null;
		dsTable.Rows.Add(row);
	}
	private void BindToColumns(DataTable metaData)
	{
		if(false == _fieldsBound)
		{
			if(metaData.Columns.Contains("TABLE_CATALOG"))			f_Catalog			 = metaData.Columns["TABLE_CATALOG"];
			if(metaData.Columns.Contains("TABLE_SCHEMA"))			f_Schema			 = metaData.Columns["TABLE_SCHEMA"];
			if(metaData.Columns.Contains("TABLE_NAME"))				f_TableName			 = metaData.Columns["TABLE_NAME"];
			if(metaData.Columns.Contains("INDEX_CATALOG"))			f_IndexCatalog		 = metaData.Columns["INDEX_CATALOG"];
			if(metaData.Columns.Contains("INDEX_SCHEMA"))			f_IndexSchema		 = metaData.Columns["INDEX_SCHEMA"];
			if(metaData.Columns.Contains("INDEX_NAME"))				f_IndexName			 = metaData.Columns["INDEX_NAME"];
			if(metaData.Columns.Contains("UNIQUE"))					f_Unique			 = metaData.Columns["UNIQUE"];
			if(metaData.Columns.Contains("CLUSTERED"))				f_Clustered			 = metaData.Columns["CLUSTERED"];
			if(metaData.Columns.Contains("TYPE"))					f_Type				 = metaData.Columns["TYPE"];
			if(metaData.Columns.Contains("FILL_FACTOR"))			f_FillFactor		 = metaData.Columns["FILL_FACTOR"];
			if(metaData.Columns.Contains("INITIAL_SIZE"))			f_InitializeSize	 = metaData.Columns["INITIAL_SIZE"];
			if(metaData.Columns.Contains("NULLS"))					f_Nulls				 = metaData.Columns["NULLS"];
			if(metaData.Columns.Contains("SORT_BOOKMARKS"))			f_SortBookmarks		 = metaData.Columns["SORT_BOOKMARKS"];
			if(metaData.Columns.Contains("AUTO_UPDATE"))			f_AutoUpdate		 = metaData.Columns["AUTO_UPDATE"];
			if(metaData.Columns.Contains("NULL_COLLATION"))			f_NullCollation		 = metaData.Columns["NULL_COLLATION"];
			if(metaData.Columns.Contains("COLLATION"))				f_Collation			 = metaData.Columns["COLLATION"];
			if(metaData.Columns.Contains("CARDINALITY"))			f_Cardinality		 = metaData.Columns["CARDINALITY"];
			if(metaData.Columns.Contains("PAGES"))					f_Pages				 = metaData.Columns["PAGES"];
			if(metaData.Columns.Contains("FILTER_CONDITION"))		f_FilterCondition	 = metaData.Columns["FILTER_CONDITION"];
			if(metaData.Columns.Contains("INTEGRATED"))				f_Integrated		 = metaData.Columns["INTEGRATED"];
		}
	}
 public static DataTable Ilceler(int id)
 {
     try
     {
         using (baglan = new SqlConnection(ConnectionString))
         {
             baglan.Open();
             using (komutver = new SqlCommand())
             {
                 komutver.Connection = baglan;
                 komutver.CommandText = "ilce_Listele";
                 komutver.Parameters.Add("@ilceId", SqlDbType.Int);
                 komutver.Parameters["@ilceId"].Value = Convert.ToInt32(id);
                 komutver.CommandType = CommandType.StoredProcedure;
                 adp = new SqlDataAdapter(komutver);
                 dt = new DataTable();
                 adp.Fill(dt);
             }
         }
     }
     catch (Exception)
     {
         throw;
     }
     return dt;
 }
Пример #15
0
        public static void Test(IMyMetaTestContext criteria)
        {
            IMyMetaPlugin plugin = null;

            try
            {
                plugin = dbRoot.Plugins[criteria.ProviderType] as IMyMetaPlugin;

                IMyMetaPluginContext context = new MyMetaPluginContext(plugin.ProviderUniqueKey, criteria.ConnectionString);

                plugin.Initialize(context);
                using (IDbConnection conn = plugin.NewConnection)
                {
                    conn.Open();
                    conn.Close();
                }
                criteria.AppendLog("Connection Test Successful.");
            }
            catch (Exception ex)
            {
                criteria.AppendLog("Error testing connection", ex);
            }

            _databases = null;
            TestDatabases(criteria, plugin);
            TestTables(criteria, plugin);
            TestViews(criteria, plugin);
            TestProcedures(criteria, plugin);
            _databases = null;
        }
Пример #16
0
        public void ExcuteSQLBulkCopy(DataTable Datatable, string TableName, ConnectionState connectionstate, ref bool executionSucceeded)
        {
            try
            {
                if (objConnection.State == System.Data.ConnectionState.Closed)
                {
                    objConnection.Open();
                }

                SqlBulkCopy.BatchSize = Datatable.Rows.Count;
                SqlBulkCopy.BulkCopyTimeout = 0;
                SqlBulkCopy.DestinationTableName = TableName;
                SqlBulkCopy.WriteToServer(Datatable);
                SqlBulkCopy.Close();
                executionSucceeded = true;
            }
            catch (Exception ex)
            {
                executionSucceeded = false;
                HandleExceptions(ex);
            }
            finally
            {
                //SqlBulkCopy.ColumnMappings.Clear();

                if (connectionstate == ConnectionState.CloseOnExit)
                {
                    if (objConnection.State == System.Data.ConnectionState.Open)
                    {
                        objConnection.Close();
                    }
                }
            }
        }
Пример #17
0
        private static DataTable GetDatabases(IMyMetaTestContext criteria, IMyMetaPlugin plugin)
        {
            if (_databases == null)
            {
                _databases = plugin.Databases;
                if (criteria.DefaultDatabaseOnly)
                {
                    List<DataRow> rowsToDelete = new List<DataRow>();
                    string defaultDb = plugin.DefaultDatabase;
                    if (!string.IsNullOrEmpty(defaultDb))
                    {
                        defaultDb = defaultDb.Trim();
                        foreach (DataRow dbRow in _databases.Rows)
                        {
                            string dbname = dbRow["CATALOG_NAME"].ToString();
                            if (dbname != defaultDb) rowsToDelete.Add(dbRow);
                        }
                    }
                    if (rowsToDelete.Count != (_databases.Rows.Count - 1))
                    {
                        rowsToDelete.Clear();
                        for (int i = 1; i < _databases.Rows.Count; i++) rowsToDelete.Add(_databases.Rows[i]);
                    }

                    foreach (DataRow dbRow in rowsToDelete) _databases.Rows.Remove(dbRow);
                }
            }
            return _databases;
        }
Пример #18
0
 /// <summary>
 /// constructor optionally calls method to init the row information structure 
 /// and return the itself - singleton
 /// </summary>
 /// <param name="dt">table to gather info on</param>
 /// <param name="init">if true, initialize; for example, on import</param>
 /// <returns></returns>
 public static dtRowInformation getdtRI(DataTable dt, bool init)
 {
     //pass null after initialization to access the DTRowInfo property
     //or pass init=true (after import) to initialize
     if (dtRI == null || init) dtRI = new dtRowInformation(dt);
     return dtRI;
 }
Пример #19
0
        public string InsertKhachHang(string TenKH, string Gioitinh, string Diachi, string SDT, string LoaiKH, string Ghichu)
        {
            string str = "";
            string sql = "InsertKH";
            //   string sql = "insert NhomSP values (@Manhom, @Tennhom, @NgayCN)";
            SqlConnection con = new SqlConnection(KetNoiDB.getconnect());
            con.Open();
            SqlCommand cmd = new SqlCommand(sql, con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@TenKH", TenKH);
            cmd.Parameters.AddWithValue("@gt", Gioitinh);
            cmd.Parameters.AddWithValue("@DC", Diachi);
            cmd.Parameters.AddWithValue("@SDT", SDT);
            cmd.Parameters.AddWithValue("@LoaiKH", LoaiKH);
            cmd.Parameters.AddWithValue("@ghichu", Ghichu);
            //cmd.ExecuteNonQuery();

            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            str = dt.Rows[0].ItemArray[0].ToString();

            cmd.Dispose();
            con.Close();

            return str;
        }
Пример #20
0
        private void MenuFileOpen_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string filename = openFileDialog.FileName;
                string extension = Path.GetExtension(filename);
                if (extension == ".xls" || extension == ".xlsx")
                {
                    ExcelReader db = new ExcelReader(filename, true, false);
                    TableSelectDialog t = new TableSelectDialog(db.GetWorksheetList());

                    if (t.ShowDialog(this) == DialogResult.OK)
                    {
                        this.sourceTable = db.GetWorksheet(t.Selection);
                        this.dgvAnalysisSource.DataSource = sourceTable;

                        this.comboBox1.Items.Clear();
                        this.checkedListBox1.Items.Clear();
                        foreach (DataColumn col in sourceTable.Columns)
                        {
                            this.comboBox1.Items.Add(col.ColumnName);
                            this.checkedListBox1.Items.Add(col.ColumnName);
                        }

                        this.comboBox1.SelectedIndex = 0;
                    }
                }
            }
        }
Пример #21
0
        public static string UpdateSagaXMLFile(ref DataTable _XMLDt, string XMLpath)
        {
            try
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(XMLpath);

                XmlNode xmlnode = xmldoc.DocumentElement.ChildNodes[0];
                xmlnode["ODBCDriverName"].InnerText = _XMLDt.Rows[0]["ODBCDriverName"].ToString();
                xmlnode["HostName"].InnerText = _XMLDt.Rows[0]["HostName"].ToString();
                xmlnode["ServerName"].InnerText = _XMLDt.Rows[0]["ServerName"].ToString();
                xmlnode["ServiceName"].InnerText = _XMLDt.Rows[0]["ServiceName"].ToString();
                xmlnode["Protocol"].InnerText = _XMLDt.Rows[0]["Protocol"].ToString();
                xmlnode["DatabaseName"].InnerText = _XMLDt.Rows[0]["DatabaseName"].ToString();
                xmlnode["UserId"].InnerText = _XMLDt.Rows[0]["UserId"].ToString();
                xmlnode["Password"].InnerText = _XMLDt.Rows[0]["Password"].ToString();
                xmlnode["ClientLocale"].InnerText = _XMLDt.Rows[0]["ClientLocale"].ToString();
                xmlnode["DatabaseLocale"].InnerText = _XMLDt.Rows[0]["DatabaseLocale"].ToString();

                xmldoc.Save(XMLpath);

                return "";
            }
            catch (Exception err)
            {
                return err.Message;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //  if (ConfigurationManager.AppSettings["ISONHOLIDAY"] == "Yes")
            var menuItems = (from all in context.Items select all);
            if (!IsPostBack)
            {
                DataTable table = new DataTable();
                table.Columns.Add("Name", typeof(string));
                table.Columns.Add("Ingredients", typeof(string));
                table.Columns.Add("Price", typeof(decimal));

                DataRow row;

                foreach (var item in menuItems)
                {
                    row = table.NewRow();
                    row["Name"] = item.Name;
                    row["Ingredients"] = item.Ingredients;
                    row["Price"] = item.Price.ToString("#0.00");
                    table.Rows.Add(row);
                }
                
                MainMenuGrid.DataSource = table;
                MainMenuGrid.DataBind();
            }
        }
Пример #23
0
        /// <summary>
        /// �����ݼ�������Ϊexcel
        /// </summary>
        /// <param name="name">����excel������</param>
        /// <param name="ds">�����������ݼ�</param>
        public static void AddExcel(string name, DataTable dt)
        {
            string fileName = name + ".xls";
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
            int rowIndex = 1;
            int colIndex = 0;
            excel.Application.Workbooks.Add(true);
            foreach (DataColumn col in dt.Columns)
            {
                colIndex++;
                excel.Cells[1, colIndex] = col.ColumnName;
            }

            foreach (DataRow row in dt.Rows)
            {
                rowIndex++;
                colIndex = 0;
                for (colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
                {
                    excel.Cells[rowIndex, colIndex + 1] = row[colIndex].ToString();
                }
            }

            excel.Visible = false;
            excel.ActiveWorkbook.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
            excel.Quit();
            excel = null;
            GC.Collect();//��������
        }
Пример #24
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                MySqlConnection myConn = new MySqlConnection();
                myConn.Host = "192.168.69.8";
                myConn.Port = 3306;
                myConn.UserId = "cody";
                myConn.Password = "greenstreetelite";
                myConn.Open();

                MySqlCommand myCommand = new MySqlCommand(" SELECT * FROM registration.regUser ;", myConn);
                MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
                myDataAdapter.SelectCommand = myCommand;
                DataTable dbDataSet = new DataTable();
                myDataAdapter.Fill(dbDataSet);
                BindingSource bSource = new BindingSource();

                bSource.DataSource = dbDataSet;
                dataGridView1.DataSource = bSource;
                myDataAdapter.Update(dbDataSet);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #25
0
        public DataTable ObtenerDatos(String ComandoSql)
        {
            SqlDataAdapter adapter;
            DataTable dt = new DataTable();

            try
            {
                con.Open();
                Cmd.Connection = con;
                Cmd.CommandText = ComandoSql;

                adapter = new SqlDataAdapter(Cmd);
                adapter.Fill(dt);

            }
            catch (Exception ex)
            {
                throw ex;
                //MessageBox.Show(ex.Message);
            }
            finally
            {
                con.Close();
            }

            return dt;
        }
Пример #26
0
        private void cbxclub_DropDownOpened(object sender, EventArgs e)
        {
            try
            {
                if (cbxseason.SelectedItem == null || cbxzone.SelectedItem == null || cbxdivision.SelectedItem == null)
                {
                    MessageBox.Show("Select Season, Zone, Division");
                }

                string strRetrieve = "";
                strRetrieve = "select * from clubdetails";
                //  cbxclub.Items.Clear();
                OleDbDataAdapter adpt = new OleDbDataAdapter(strRetrieve, Database.getConnection());
                DataTable dt = new DataTable();
                adpt.Fill(dt);

                foreach (DataRowView dr in dt.DefaultView)
                {
                    //   List<Team> lstFilter = Database.GetEntityList<Team>( false, false,false,Database.getConnection(),RecordStatus true);
                    //cbxclub.Items.Add(dr["ClubName"]);
                    //cbxteam.Items.Refresh();

                    if (!cbxclub.Items.Contains(dr["ClubName"]))// For remove list duplicacy
                    {
                        cbxclub.Items.Add(dr["ClubName"]);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #27
0
        /// <summary>
        /// 生成DAL带命名空间
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="dt"></param>
        /// <param name="strNamespace"></param>
        /// <returns></returns>
        public StringBuilder CreateDALCode(string tableName, DataTable dt, string strNamespace)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("using "+ strNamespace + ".IDAL.Bases;");
            sb.AppendLine("using " + strNamespace + ".DAL.Bases;");
            sb.AppendLine("using "+ strNamespace + ".Models;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("using System;");
            sb.AppendLine("using System.Data;");
            string sqluse = sqltype == 2 ? "using MySql.Data.MySqlClient;" : "using System.Data.SqlClient;";
            sb.AppendLine(sqluse);
            sb.AppendLine("");
            sb.AppendLine("namespace " + strNamespace + ".DAL {");
            string cName = ":MsSqlDALConf";
            if (sqltype == (int)SQLType.MySql)
            {
                cName = ":MySqlDALConf";
            }
            sb.AppendLine("public  class  " + tableName + "DAL " + cName + ", I"+ tableName + "DAL{");
            sb.AppendLine("");
            sb.AppendLine("        public "+ tableName + "DAL() : base() { }");
            sb.AppendLine("        public " + tableName + "DAL(string name) : base(name) { }");

            GetAllDAL(tableName, dt, sb, "    ");
            sb.AppendLine("    }");
            sb.AppendLine("}");
            return sb;
        }
        public void challanout()
        {
            DataTable dt = new DataTable("challandt");
            dt = (DataTable)Session["challanout_dt"];

            DataSet ds = new DataSet();
            Viewer.Report.ChallanOutrpt crystalReport = new Report.ChallanOutrpt();
            string st = HttpContext.Current.Server.MapPath("~/ChallanOutCrpt1.rpt");

            //  Label1.Text = st;
            //   Response.Write(string.Format("<script language='javascript' type='text/javascript'>alert( "+st+") </script>"));

            crystalReport.Load(st);
            if (ds.Tables.Contains("challandt") == true)
            {
                ds.Tables.Remove("challandt");
            }
            ds.Tables.Add(dt);

            ds.WriteXmlSchema(HttpContext.Current.Server.MapPath("~/App_Data/Challanout.xml"));

            crystalReport.SetDataSource(dt);
            CrystalReportViewer1.ReportSource = crystalReport;

            crystalReport.ExportToHttpResponse
               (CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Response, true, "CHALLANOUTSHEET");
        }
Пример #29
0
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<HisClient.Model.his_pm_import> DataTableToList(DataTable dt)
        {
            List<HisClient.Model.his_pm_import> modelList = new List<HisClient.Model.his_pm_import>();
            int rowsCount = dt.Rows.Count;
            if (rowsCount > 0)
            {
                HisClient.Model.his_pm_import model;
                for (int n = 0; n < rowsCount; n++)
                {
                    model = new HisClient.Model.his_pm_import();
                                                                    model.ID= dt.Rows[n]["ID"].ToString();
                                                                                                                                model.SEND_DEPT_CODE= dt.Rows[n]["SEND_DEPT_CODE"].ToString();
                                                                                                                                model.RECEIVE_DEPT_CODE= dt.Rows[n]["RECEIVE_DEPT_CODE"].ToString();
                                                                                                                                model.PAKAGE_OUT_CODE= dt.Rows[n]["PAKAGE_OUT_CODE"].ToString();
                                                                                                                                model.CREATE_BY= dt.Rows[n]["CREATE_BY"].ToString();
                                                                                                                if(dt.Rows[n]["CREATE_DATE"].ToString()!="")
                {
                    model.CREATE_DATE=DateTime.Parse(dt.Rows[n]["CREATE_DATE"].ToString());
                }
                                                                                                                                                model.IMPORT_CODE= dt.Rows[n]["IMPORT_CODE"].ToString();

                    modelList.Add(model);
                }
            }
            return modelList;
        }
Пример #30
0
 public static Task CreateTaskByTable(DataTable dt)
 {
     Task task = null;
     try
     {
         task = new Task();
         task.TaskNo = (dt.Rows[0]["TaskNo"] == null ? "" : dt.Rows[0]["TaskNo"].ToString());
         task.BatchNo = (dt.Rows[0]["BatchNo"] == null ? "" : dt.Rows[0]["BatchNo"].ToString());
         task.ItemNo = (dt.Rows[0]["ItemNo"] == null ? "" : dt.Rows[0]["ItemNo"].ToString());
         task.ItemName = (dt.Rows[0]["ItemName"] == null ? "" : dt.Rows[0]["ItemName"].ToString());
         task.Sn = (dt.Rows[0]["Sn"] == null ? "" : dt.Rows[0]["Sn"].ToString());
         task.PV = (dt.Rows[0]["PV"] == null ? 0 : int.Parse(dt.Rows[0]["PV"].ToString()));
         task.Result = (dt.Rows[0]["Result"] == null ? 0 : int.Parse(dt.Rows[0]["Result"].ToString()));
         task.redundantVaue = (dt.Rows[0]["RedundantVaue"] == null ? 0 : int.Parse(dt.Rows[0]["RedundantVaue"].ToString()));
         IFormatProvider ifp = new CultureInfo("zh-CN", true);
         if (dt.Rows[0]["StartTime"] != null)
         {
             DateTime.TryParseExact(dt.Rows[0]["StartTime"].ToString(), DateTimeFormat2, ifp, DateTimeStyles.None, out task.StartTime);
         }
         if (dt.Rows[0]["CompleteTime"] != null)
         {
             DateTime.TryParseExact(dt.Rows[0]["CompleteTime"].ToString(), DateTimeFormat2, ifp, DateTimeStyles.None, out task.CompleteTime);
         }
         return task;
     }
     catch (Exception ex)
     {
         Program.WriteErrorLog("CreateTaskByTable", ex);
         return task;
     }
 }