protected int getTotalCount() { SqlConnection connection = new SqlConnection(GetConnectionString()); DataTable dt = new DataTable(); try { connection.Open(); string sqlStatement = "SELECT * FROM tblContact"; SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection); SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd); sqlDa.Fill(dt); } catch (System.Data.SqlClient.SqlException ex) { string msg = "Fetch Error:"; msg += ex.Message; throw new Exception(msg); } finally { connection.Close(); } return dt.Rows.Count; }
/// <summary> /// ดึงรายชื่อพนักงานตามเงื่อนไขที่กำหนด เพื่อนำไปแสดงบนหน้า ConvertByPayor /// </summary> /// <param name="doeFrom"></param> /// <param name="doeTo"></param> /// <param name="payor"></param> /// <returns></returns> public DataTable getPatient(DateTime doeFrom,DateTime doeTo,string payor,string mobileStatus) { System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); #region Variable var dt = new DataTable(); var strSQL = new StringBuilder(); var clsSQL = new clsSQLNative(); #endregion #region Procedure #region SQLQuery strSQL.Append("SELECT "); strSQL.Append("No,HN,PreName,Name,LastName,DOE,Payor,SyncWhen,'0' IsConvertPreOrder "); strSQL.Append("FROM "); strSQL.Append("Patient P "); strSQL.Append("WHERE "); strSQL.Append("(DOE BETWEEN '" + doeFrom.ToString("yyyy-MM-dd HH:mm") + "' AND '" + doeTo.ToString("yyyy-MM-dd HH:mm") + "') "); if(payor!="" && payor.ToLower() != "null") { strSQL.Append("AND Payor='"+payor+"' "); } if (mobileStatus == "NotRegister") { strSQL.Append("AND SyncStatus!='1' "); } else if (mobileStatus == "Register") { strSQL.Append("AND SyncStatus='1' "); } strSQL.Append("ORDER BY "); strSQL.Append("No;"); #endregion dt = clsSQL.Bind(strSQL.ToString(), clsSQLNative.DBType.SQLServer, "MobieConnect"); #endregion return dt; }
private void Page_PreRender() { // Create a DataTable and define its columns DataTable RoleList = new DataTable(); RoleList.Columns.Add("Role Name"); RoleList.Columns.Add("User Count"); string[] allRoles = Roles.GetAllRoles(); // Get the list of roles in the system and how many users belong to each role foreach (string roleName in allRoles) { int numberOfUsersInRole = Roles.GetUsersInRole(roleName).Length; string[] roleRow = { roleName, numberOfUsersInRole.ToString() }; RoleList.Rows.Add(roleRow); } // Bind the DataTable to the GridView UserRoles.DataSource = RoleList; UserRoles.DataBind(); if (createRoleSuccess) { // Clears form field after a role was successfully added. NewRole.Text = ""; } }
public DataTable listarSucursales() { SqlDataAdapter da = new SqlDataAdapter("select * from tb_sucursal", cn.getCn); DataTable tb = new DataTable(); da.Fill(tb); return tb; }
protected void btnConvertRowstoColumns_Click(object sender, EventArgs e) { DataTable dTable = (DataTable)ViewState["dTable"]; if ((sender as Button).CommandArgument == "RowstoColumns") { DataTable dTable2 = new DataTable(); for (int i = 0; i <= dTable.Rows.Count; i++) { dTable2.Columns.Add(); } for (int i = 0; i < dTable.Columns.Count; i++) { dTable2.Rows.Add(); dTable2.Rows[i][0] = dTable.Columns[i].ColumnName; } for (int i = 0; i < dTable.Columns.Count; i++) { for (int j = 0; j < dTable.Rows.Count; j++) { dTable2.Rows[i][j + 1] = dTable.Rows[j][i]; } } btnConvertRowstoColumns.Visible = false; btnConvertColumnstoRows.Visible = true; BindGridViewData(dTable2, true); } else { btnConvertRowstoColumns.Visible = true; btnConvertColumnstoRows.Visible = false; BindGridViewData(dTable, false); } }
protected void btnLogin_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt = objBAL.GetLoginDetails(username.Text, password.Text); Session["dt"] = dt; if (dt.Rows.Count > 0) { if (dt.Rows[0]["Approved"].ToString() == "Yes") { count = 0; lblMsg.Text = "Login Successfull"; Session["username"] = dt.Rows[0]["Username"].ToString(); Session["ID"] = dt.Rows[0]["ID"].ToString(); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "Login Successfull", true); Response.Redirect("QRCode.aspx"); } else { lblMsg.Text = "Admin didn't approve you. Wait for approval..."; } } else { count++; lblMsg.Text = "Login Failed!!!"; //int id=Convert.ToInt32(dt.Rows[0]["UserID"]); if ((count > 3))// && (id!=3)) { //objBAL.updateapprovedetails(id); lblMsg.Text = "Password has been mistyped 3 times...Wait for Admin to approve you!!!"; } } }
protected void grdvwViewAsset_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName.Equals("AlphaPaging")) { string commandname = e.CommandArgument.ToString(); ViewState["commandname"] = e.CommandArgument.ToString(); col = ObjAsset.Get_By_comandname(commandname); if (col.Count != 0) { grdvwViewAsset.DataSource = col; grdvwViewAsset.DataBind(); } else { DataTable dt = new DataTable(); dt.Columns.Add("assetid"); dt.Columns.Add("computername"); dt.Columns.Add("domain"); DataRow dr = dt.NewRow(); dt.Rows.Add(dr); grdvwViewAsset.DataSource = dt; grdvwViewAsset.DataBind(); //grdvwViewAsset.Rows[0].Cells[3].Visible = false; //grdvwViewAsset.Rows[0].Cells[5].Visible = false; } } }
protected void GridViewBind() { DataTable dt = new DataTable(); dt = BLL.X7_DZX_SeleteByNum(30); GridView1.DataSource = dt; GridView1.DataBind(); }
protected void Fill_User_Header() { DataView view = null; SqlConnection con; SqlCommand cmd = new SqlCommand(); DataSet ds = new DataSet(); DataTable dt = new DataTable(); System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/BitOp"); System.Configuration.ConnectionStringSettings connString; connString = rootWebConfig.ConnectionStrings.ConnectionStrings["BopDBConnectionString"]; con = new SqlConnection(connString.ToString()); cmd.Connection = con; con.Open(); string sql = @"SELECT Fecha_Desde, Inicio_Nombre, Region, Supervisor FROM Criterios WHERE Criterio_ID = " + @Criterio_ID; SqlDataAdapter da = new SqlDataAdapter(sql, con); da.Fill(ds); dt = ds.Tables[0]; view = new DataView(dt); foreach (DataRowView row in view) { Lbl_Fecha_Desde.Text = row["Fecha_Desde"].ToString("dd-MM-yyyy"); Lbl_Inicio_Descrip.Text = row["Inicio_Nombre"].ToString(); Lbl_Region.Text = row["Region"].ToString(); Lbl_Supervisor.Text = row["Supervisor"].ToString(); } con.Close(); }
protected void btnSave_Click(object sender, EventArgs e) { dtgridList = (DataTable)ViewState["dtgridList"]; string users = Session["id"].ToString(); FrameWork.DRSIForm drsi = new FrameWork.DRSIForm(); FrameWork.DRSISub drsisub = new DRSISub(); busDISRForm busDISR = new busDISRForm(); drsi.CustomerFKID = int.Parse(this.drpCustomer.SelectedValue); drsi.ProductFKID = int.Parse(this.drpProduct.SelectedValue); drsi.TotalPcs = lblPcs.Text; drsi.TotalUOM = lblUOM.Text; drsi.TotalWeight = lblWeight.Text; drsi.TotalUnitCost = txtCost.Text; drsi.TotalCost = lblTCost.Text; drsi.OrderBy = users; string x = busDISR.insertDRSI(drsi); foreach (DataRow dr in dtgridList.Rows) { drsisub.DRSiformID = int.Parse(x); drsisub.BatchNo = dr["BatchNo"].ToString(); drsisub.ModuleNo = dr["ModuleNo"].ToString(); drsisub.CageNo = dr["CageNo"].ToString(); drsisub.Weight = dr["Weight"].ToString(); drsisub.UnitOfMeasure = dr["UnitOfMeasure"].ToString(); busDISR.insertDRSIsub(drsisub); } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Id = Request.QueryString["Id"] == null ? "" : Request.QueryString["Id"] == "" ? "" : Request.QueryString["Id"]; if (Id == "2") { categoryLevel1 = DataAccess.GetDatatable("select * from fnGetAllChildHaveFilter(2)"); categoryByParentId = DataAccess.GetDatatable("select * from Category where CategoryID =2"); if (string.IsNullOrEmpty(ltrContent.Text)) ltrContent.Text = categoryByParentId.Rows[0]["DescriptionCAM"].ToString(); } else { categoryById = DataAccess.GetDatatable("select * from fnGetAllChild(" + Id + ")"); string para = ""; if (categoryById.Rows.Count > 0) { para = categoryById.Rows[0]["ParentID"].ToString(); } else { categoryById = DataAccess.GetDatatable("select * from Category where CategoryID =" + Id); para = categoryById.Rows[0]["ParentID"].ToString(); ltrContent.Text = categoryById.Rows[0]["DescriptionCAM"].ToString(); } categoryByParentId = DataAccess.GetDatatable("select * from Category where CategoryID =" + para); if (string.IsNullOrEmpty(ltrContent.Text)) ltrContent.Text = categoryByParentId.Rows[0]["DescriptionCAM"].ToString(); } } }
private void CreateTempTable() { tempTable = new DataTable(); DataColumn dcORDERNO = new DataColumn("ORDERNO"); DataColumn dcBARCODE = new DataColumn("BARCODE"); DataColumn dcNAME = new DataColumn("PRODUCTNAME"); DataColumn dcQUANTITY = new DataColumn("QUANTITY"); DataColumn dcUNIT = new DataColumn("UNIT"); DataColumn dcCOST = new DataColumn("COST"); DataColumn dcPRICE = new DataColumn("PRICE"); DataColumn dcSTDPRICE= new DataColumn("STDPRICE"); DataColumn dcLOID = new DataColumn("LOID"); DataColumn dcPUNIT = new DataColumn("PUNIT"); tempTable.Columns.Add(dcORDERNO); tempTable.Columns.Add(dcBARCODE); tempTable.Columns.Add(dcNAME); tempTable.Columns.Add(dcQUANTITY); tempTable.Columns.Add(dcUNIT); tempTable.Columns.Add(dcCOST); tempTable.Columns.Add(dcPRICE); tempTable.Columns.Add(dcSTDPRICE); tempTable.Columns.Add(dcLOID); tempTable.Columns.Add(dcPUNIT); }
public DataTable IntroPageBuilder() { #region Variable var strSQL = new StringBuilder(); var dt = new DataTable(); #endregion #region Procedure #region SQLQuery strSQL.Append("SELECT "); strSQL.Append("Photo,Name "); strSQL.Append("FROM "); strSQL.Append("IntroPage "); strSQL.Append("WHERE "); strSQL.Append("StatusFlag='A' "); strSQL.Append("AND (("); strSQL.Append("ActiveIgnoreYear='0' "); strSQL.Append("AND (ActiveFrom IS NULL OR ActiveFrom <= GETDATE()) "); strSQL.Append("AND (ActiveTo IS NULL OR ActiveTo >= GETDATE())"); strSQL.Append(") "); strSQL.Append("OR ("); strSQL.Append("ActiveIgnoreYear='1' "); strSQL.Append("AND (ActiveFrom IS NULL OR CONVERT(DATETIME,CONVERT(VARCHAR,DATEPART(YEAR,GETDATE()))+'-'+CONVERT(VARCHAR,DATEPART(MONTH,ActiveFrom))+'-'+CONVERT(VARCHAR,DATEPART(DAY,ActiveFrom))) <= GETDATE()) "); strSQL.Append("AND (ActiveTo IS NULL OR CONVERT(DATETIME,CONVERT(VARCHAR,DATEPART(YEAR,GETDATE()))+'-'+CONVERT(VARCHAR,DATEPART(MONTH,ActiveTo))+'-'+CONVERT(VARCHAR,DATEPART(DAY,ActiveTo))) >= GETDATE())"); strSQL.Append(")) "); strSQL.Append("ORDER BY "); strSQL.Append("Sort ASC;"); #endregion dt = clsSQL.Bind(strSQL.ToString(), dbType, cs); #endregion return dt; }
protected void Buscar() { Ocultar(); registroContrato _contrato = new registroContrato(Session["idEmpresa"].ToString(), Session["USU_LOG"].ToString()); DataTable _dataTable = new DataTable(); switch (this.DropDownList_BUSCAR.SelectedValue) { case "NUMERO_DOCUMENTO": _dataTable = _contrato.ObtenerPorNumeroIdentificacion(this.TextBox_BUSCAR.Text); break; case "NOMBRE": _dataTable = _contrato.ObtenerPorNombre(this.TextBox_BUSCAR.Text); break; } if (_dataTable.Rows.Count > 0) { GridView_RESULTADOS_BUSQUEDA.DataSource = _dataTable; GridView_RESULTADOS_BUSQUEDA.DataBind(); Mostrar(Acciones.BusquedaEncontro); } else { if (!String.IsNullOrEmpty(_contrato.MensajeError)) Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, "Error: Consulte con el Administrador: " + _contrato.MensajeError, Proceso.Error); else Informar(Panel_FONDO_MENSAJE, Image_MENSAJE_POPUP, Panel_MENSAJES, Label_MENSAJE, "ADVERTENCIA: No se encontró información para " + this.DropDownList_BUSCAR.SelectedItem + " : " + this.TextBox_BUSCAR.Text + "<br />" + "Causa: 1. La información ingresada no es correcta." + "<br />" + "Causa: 2. No tiene contrato.", Proceso.Correcto); Mostrar(Acciones.BusquedaNoEncontro); } _dataTable.Dispose(); }
public void getMpdata(Int16 constituencyId) { try { DataTable dt = new DataTable(); dt = mpdetailsbal.getData(constituencyId); /** empid fetch throw ***/ imgMpProfile.ImageUrl = dt.Rows[0]["profilePic"].ToString(); lblname.Text = dt.Rows[0]["firstName"].ToString() + " " + dt.Rows[0]["middleName"].ToString() + " " + dt.Rows[0]["lastName"].ToString(); lblconstituency.Text = dt.Rows[0]["constituency"].ToString(); lblparty.Text = dt.Rows[0]["partyName"].ToString() + "(" + dt.Rows[0]["Abbreviation"].ToString() + ")"; lblmail.Text = dt.Rows[0]["email"].ToString(); lblcntct.Text = dt.Rows[0]["mobile"].ToString(); lbleducational_q.Text = dt.Rows[0]["qualification"].ToString(); lblprofession.Text = dt.Rows[0]["profession"].ToString(); lblp_address.Text = dt.Rows[0]["permanentAddress"].ToString() + ", " + dt.Rows[0][12].ToString() + ", " + dt.Rows[0][13].ToString(); lblpresent_address.Text = dt.Rows[0]["currentAddress"].ToString() + ", " + dt.Rows[0][15].ToString() + ", " + dt.Rows[0][16].ToString(); mpidval = Int64.Parse(dt.Rows[0]["mpId"].ToString()); //DataTable numDt = new DataTable(); //numDt = issuesbal.Issues_Numbers(Convert.ToInt64(dt.Rows[0]["mpId"])); //lblissuesno.Text = numDt.Rows[0][0].ToString(); //lblsolvedissuesno.Text = numDt.Rows[0][1].ToString(); } catch { throw; } finally { } }
public DataTable GetAllProducts() { DataTable dt = new DataTable(); DataRow dr; DataColumn dc; dc = new DataColumn("ID", typeof(Int32)); dc.Unique = true; dt.Columns.Add(dc); dt.Columns.Add(new DataColumn("ProductName", typeof(string))); dt.Columns.Add(new DataColumn("Description", typeof(string))); dt.Columns.Add(new DataColumn("Price", typeof(string))); for (int i = 0; i < 10000; i++) { dr = dt.NewRow(); dr["id"] = i; dr["ProductName"] = "Product " + i; dr["Description"] = "Description for Product " + i; dr["Price"] = "$100"; dt.Rows.Add(dr); } return dt; }
protected void btnclick(object sender, EventArgs e) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString); con.Open(); var com = new SqlCommand("select mail_id from user_details where otp=@otp", con); com.Parameters.AddWithValue("@otp", otp.Text); SqlDataAdapter da = new SqlDataAdapter(com); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count > 0) { var s = com.ExecuteScalar(); string a = s.ToString(); SqlCommand cmd = new SqlCommand("update user_details set pwd=@otpp where mail_id=@username", con); cmd.Parameters.AddWithValue("@username", a); cmd.Parameters.AddWithValue("@otpp", TextBox3.Text); cmd.ExecuteNonQuery(); ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Password changed sucessfully');window.location ='login.aspx';", true); } else { error.Visible = true; } }
protected void btnsave_Click(object sender, EventArgs e) { DataTable dtMealTemplate = new DataTable(); SqlDataProvider db = new SqlDataProvider(); dtMealTemplate.Columns.Add("Userid", Type.GetType("System.Int32")); dtMealTemplate.Columns.Add("Emailid", Type.GetType("System.String")); foreach (GridViewRow gvr in grdvwSite.Rows) { ///DataRow drMT = new DataRow(); DataRow drMT = dtMealTemplate.NewRow(); drMT["Userid"] = gvr.Cells[1].Text; drMT["Emailid"] = gvr.Cells[4].Text; dtMealTemplate.Rows.Add(drMT); CheckBox myCheckBox = (CheckBox)gvr.FindControl("CheckAll"); if (myCheckBox.Checked == true) { UserEmail obj1 = new UserEmail(); objuseremail.Userid = Convert.ToInt16(drMT["Userid"]); objuseremail.Emailid = drMT["Emailid"].ToString(); objsentuseremail.SentFeedbackmailToUser(objuseremail.Userid, objuseremail.Emailid); objuseremail.InsertFeedbackCustomer(); } } }
/// <summary> /// To check user is authorised or not from database /// </summary> /// <returns></returns> public DataTable GetUserDetails() { UserBAL UserBAL = new UserBAL(); DataTable UserTable = new DataTable(); try { UserTable = UserBAL.SelectUserName(LoginUserName, LoginUserID, Ret); if (UserTable.Rows.Count > 0) { LoginUser = Convert.ToInt16(UserTable.Rows[0][0]); LogedInUser = UserTable.Rows[0][5].ToString(); ValidUser = "******"; } else { ValidUser = "******"; } } catch { } finally { UserBAL = null; } return UserTable; }
protected void btn_refresh_Click(object sender, EventArgs e) { try { string[] listFile = Directory.GetFiles(Server.MapPath("~/article/" + mabaiviet)); DataTable dt_ref = new DataTable(); dt_ref.Columns.Add(new DataColumn("num", typeof(int))); dt_ref.Columns.Add(new DataColumn("link", typeof(string))); int num = 1; foreach (string i in listFile) { string pic = Path.GetFileName(i); dt_ref.Rows.Add(num, "../article/" + mabaiviet + "/" + pic); num++; } dtl_uploadanh.DataSource = dt_ref; dtl_uploadanh.DataBind(); ddl_anhbaiviet.DataSource = dt_ref; ddl_anhbaiviet.DataTextField = "num"; ddl_anhbaiviet.DataValueField = "link"; ddl_anhbaiviet.DataBind(); } catch (Exception) { Response.Write("<script>alert('Ảnh chưa được upload')</script>"); } }
/// <summary> /// ���˵��ֶ��ظ�ֵ��������JSON��Ҫ���ַ������ /// </summary> /// <param name="dataTable">��Ҫת����datatable</param> /// <param name="fieldName">�ֶ�����</param> /// <returns>{name:'value'},{name:'value'}</returns> public static string SelectDistinct(DataTable dataTable, string fieldName) { StringBuilder sb = new StringBuilder(); int date=0; if (fieldName.ToLower().IndexOf("date")>-1) date = 1; else date = 0; bool rc = false; object lastValue = null; foreach (DataRow dr in dataTable.Select("", fieldName)) { if (lastValue == null || !(ColumnEqual(lastValue, dr[fieldName]))) { lastValue = dr[fieldName]; if (lastValue != null) { if (rc) sb.Append(","); sb.Append("{name:'"); if (date==1) sb.Append( Convert.ToDateTime(lastValue).ToShortDateString()); else sb.Append(lastValue.ToString()); sb.Append("'}"); rc = true; } } } return sb.ToString(); }
public void bindData() { string strQuery = ""; DataTable dtinformation = new DataTable(); strQuery = "select * from vw_CulpritWholeDetail order by Code"; dtinformation = objQuerycontroller.ExecuteQuery(strQuery); if (dtinformation != null) { if (dtinformation.Rows.Count > 0) { gridDefault.DataSource = dtinformation; gridDefault.DataBind(); } else { gridDefault.DataSource = null; gridDefault.EmptyDataText = "no data found"; gridDefault.DataBind(); } } else { gridDefault.DataSource = null; gridDefault.EmptyDataText = "no data found"; gridDefault.DataBind(); } }
// executes a command and returns the results as a DataTable object public static DataTable ExecuteSelectCommand(DbCommand command) { // The DataTable to be returned DataTable table; // Execute the command making sure the connection gets closed in the end try { // Open the data connection command.Connection.Open(); // Execute the command and save the results in a DataTable DbDataReader reader = command.ExecuteReader(); table = new DataTable(); table.Load(reader); // Close the reader reader.Close(); } catch (Exception ex) { Utilities.LogError(ex); throw; } finally { // Close the connection command.Connection.Close(); } return table; }
private void showData() { string ID = Request.QueryString["ID"]; int total = 0; _Page = Request.QueryString["Page"] == null ? "1" : this.IsPostBack ? "1" : Request.QueryString["Page"]; _Limit = ddlPageSize.SelectedValue; dt = DataAccess.getProjectLogo("-1", _Page, _Limit, ref total); _Total = total.ToString(); int from, to; from = _Total == "0" ? 0 : (1 + (Convert.ToInt32(_Page) - 1) * Convert.ToInt32(ddlPageSize.SelectedValue)); to = Convert.ToInt32(ddlPageSize.SelectedValue) * Convert.ToInt32(_Page) <= Convert.ToInt32(_Total) ? Convert.ToInt32(ddlPageSize.SelectedValue) * Convert.ToInt32(_Page) : Convert.ToInt32(_Total); _Status = "<span class='actived_true'>Viewing " + from.ToString() + " to " + to.ToString() + " of " + _Total + "</span>"; Pagination pg = new Pagination(); pg.Limit = Convert.ToInt32(_Limit); pg.PageNumber = Convert.ToInt32(_Page); pg.Total = Convert.ToInt64(_Total); pg.Page = "Pages"; pg.First = "|<"; pg.Next = ">"; pg.Previous = "<"; pg.Last = ">|"; pg.ItemShowNumber = 10; pg.URL = "";//Session["PageOriginal"].ToString(); _Pagination = pg.getStringPagination(); //loadColFilter(); }
public static DataTable getDataTableImagenes(int id) { OdbcConnection con = ConexionBD.ObtenerConexion(); DataSet ds = new DataSet(); List<Noticia> listaNoticias = new List<Noticia>(); DataTable dataTable = null; try { OdbcCommand cmd = new OdbcCommand("SELECT i.pathBig, i.pathSmall, i.pathMedium FROM imagen_x_noticia ixn, imagen i" + " WHERE ixn.idNoticia = " + id + " AND i.id = ixn.idImagen", con); cmd.CommandType = CommandType.Text; dataTable = new DataTable(); OdbcDataAdapter adapter = new OdbcDataAdapter(); adapter.SelectCommand = cmd; adapter.Fill(dataTable); } catch (Exception e) { throw new SportingException("Ocurrio un problema al intentar obtener las imagenes de las noticias. " + e.Message); } finally { con.Close(); } return dataTable; }
public void bindData() { string strQuery = ""; DataTable dtinformation = new DataTable(); strQuery = "select CulpritGroupID,GRoupName from CulpritGroup order by GRoupName"; dtinformation = objQuerycontroller.ExecuteQuery(strQuery); if (dtinformation != null) { if (dtinformation.Rows.Count > 0) { GridView1.DataSource = dtinformation; GridView1.DataBind(); } else { GridView1.DataSource = null; GridView1.EmptyDataText = "no data found"; GridView1.DataBind(); } } else { GridView1.DataSource = null; GridView1.EmptyDataText = "no data found"; GridView1.DataBind(); } }
private DataTable GetDataTable() { Random random = new Random(); DataTable dt = new DataTable("Tabela Teste"); dt.Columns.Add("ID", typeof(Int32)); dt.Columns.Add("Número Inteiro", typeof(Int32)); dt.Columns.Add("Número Double", typeof(Double)); dt.Columns.Add("Descrição", typeof(String)); dt.Columns.Add("Data", typeof(DateTime)); for (int i = 0; i < 20; i++) { DataRow dr = dt.NewRow(); dr["ID"] = i + 1; dr["Número Inteiro"] = random.Next(); dr["Número Double"] = random.NextDouble(); dr["Descrição"] = "sadsdadasd asd asd sa d"; dr["Data"] = DateTime.Now; dt.Rows.Add(dr); } return dt; }
protected void Button1_Click(object sender, EventArgs e) { if (con.State == ConnectionState.Closed) con.Open(); DataTable dt = new DataTable(); if (ddlGuestType.Text == "De-Activate") { cmd = new MySqlCommand("SELECT HotelKey as HotelID,HotelName,ListingType,ShortDescription,HotelImage,HotelOverview,VideoLink,PricePerDay,GoogleMapLocation,EmailID,PhoneNumber,Address,City,State,Country,Website " + " FROM Hotels Where Status='De-Activate' ", con); } else if (ddlGuestType.Text == "Activate") { cmd = new MySqlCommand("SELECT HotelKey as HotelID,HotelName,ListingType,ShortDescription,HotelImage,HotelOverview,VideoLink,PricePerDay,GoogleMapLocation,EmailID,PhoneNumber,Address,City,State,Country,Website " + " FROM Hotels Where Status='Activate' ", con); } else { cmd = new MySqlCommand("SELECT HotelKey as HotelID,HotelName,ListingType,ShortDescription,HotelImage,HotelOverview,VideoLink,PricePerDay,GoogleMapLocation,EmailID,PhoneNumber,Address,City,State,Country,Website " + " FROM Hotels ", con); } MySqlDataAdapter da = new MySqlDataAdapter(cmd); da.Fill(dt); ExportToExcel(dt, "Hotels", ddlGuestType.Text + " Hotel" ); if (con.State == ConnectionState.Open) con.Close(); }
//Create an Excel file with 2 columns: name and score: //Write a program that reads your MS Excel file through //the OLE DB data provider and displays the name and score row by row. static void Main() { OleDbConnection dbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=D:\Telerik\DataBases\HW\ADONET\06. ReadExcel\Table.xlsx;Extended Properties=""Excel 12.0 XML;HDR=Yes"""); OleDbCommand myCommand = new OleDbCommand("select * from [Sheet1$]", dbConn); dbConn.Open(); //First way //using (dbConn) - I think it is better to use dbConn in using clause, but for the demo issues i dont use using. //{ OleDbDataReader reader = myCommand.ExecuteReader(); while (reader.Read()) { string name = (string)reader["Name"]; double score = (double)reader["Score"]; Console.WriteLine("{0} - score: {1}", name, score); } //} dbConn.Close(); //Second way dbConn.Open(); Console.WriteLine(); Console.WriteLine("Second Way"); Console.WriteLine("----------"); DataTable dataSet = new DataTable(); OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [Sheet1$]", dbConn); adapter.Fill(dataSet); foreach (DataRow item in dataSet.Rows) { Console.WriteLine("{0}|{1}", item.ItemArray[0], item.ItemArray[1]); } dbConn.Close(); }
public ActionResult Index() { List <notificationModel> Noticafition = new List <notificationModel>(); OasisConnectionManager = ConfigurationManager.ConnectionStrings["OasisConnectionString"].ConnectionString; OasisConnection = new SqlConnection(OasisConnectionManager); DataTable dataTable = new DataTable(); OasisConnection.Open(); var query = "select * from messages where FK_RecieverID=" + Convert.ToInt32(Session["id"]); SqlCommand SelectCommand = new SqlCommand(query, OasisConnection); int count = 0; using (SqlDataReader rd = SelectCommand.ExecuteReader()) { Session["totalMsg"] = rd.FieldCount; while (rd.Read()) { if (rd["MsgStatus"].ToString() == "Sent") { count = count + 1; } } Session["msgNum"] = count; } if (OasisConnection.State == ConnectionState.Open) { OasisConnection.Close(); OasisConnectionManager = ConfigurationManager.ConnectionStrings["OasisConnectionString"].ConnectionString; OasisConnection = new SqlConnection(OasisConnectionManager); OasisConnection.Open(); var queryNotification = "select * from Notifications where RecieverRole='" + "ProductionEmployee" + "'"; SqlCommand SelectNotificatoinCommand = new SqlCommand(queryNotification, OasisConnection); using (SqlDataReader rd = SelectNotificatoinCommand.ExecuteReader()) { while (rd.Read()) { notificationModel notify = new notificationModel(); notify.id = Convert.ToInt32(rd["id"]); notify.RecieverRole = rd["RecieverRole"].ToString(); notify.Notification = rd["Notification"].ToString(); notify.datesent = Convert.ToDateTime(rd["datesent"]); Noticafition.Add(notify); } } } return(View(Noticafition)); }
public bool ImportaDados(DataTable dt) { return(new UsuarioDAL().ImportaDados(dt)); }
/// <summary> /// 带有分页的文章列表 /// </summary> /// <param name="searchSetting"></param> /// <returns></returns> public static IPageOfList <ArticleInfo> List(ArticleSearchSetting searchSetting) { FastPaging fp = new FastPaging(); fp.OverOrderBy = " A.PublishDateTime DESC"; fp.PageIndex = searchSetting.PageIndex; fp.PageSize = searchSetting.PageSize; fp.QueryFields = "*"; fp.TableName = "Articles"; fp.PrimaryKey = "Id"; fp.TableReName = "A"; fp.WithOptions = " WITH(NOLOCK)"; StringBuilder sbSQL = new StringBuilder(); if (searchSetting.ColumnIds != null && searchSetting.ColumnIds.Length > 0) { //过滤栏目分类 //跳过为0的值 string temp = Enumerable.Range(0, searchSetting.ColumnIds.Length).Select(i => { if (searchSetting.ColumnIds[i] > 0) { return(string.Format(" A.CategoryId = {0} ", searchSetting.ColumnIds[i])); } return(string.Empty); }).Aggregate((a, b) => a + " OR " + b); if (!string.IsNullOrEmpty(temp)) { sbSQL.AppendFormat(" AND ( {0} )", temp); } } if (searchSetting.TechIds != null && searchSetting.TechIds.Length > 0) { //过滤技术分类 string temp = Enumerable.Range(0, searchSetting.TechIds.Length).Select(i => { if (searchSetting.TechIds[i] > 0) { return(string.Format(" A2C.CategoryId = {0} ", searchSetting.TechIds[i])); } return(string.Empty); }).Aggregate((a, b) => a + " OR " + b); if (!string.IsNullOrEmpty(temp)) { sbSQL.Append(" AND EXISTS("); sbSQL.Append(" SELECT * FROM dbo.Article2Category AS A2C WITH(NOLOCK)"); sbSQL.Append(" WHERE A2C.[Type] = 'tech'"); sbSQL.Append(" AND A.Id = A2C.ArticleId"); sbSQL.AppendFormat(" AND ( {0} )", temp); sbSQL.Append(" )"); } } if (searchSetting.IndustryIds != null && searchSetting.IndustryIds.Length > 0) { //过滤行业分类 string temp = Enumerable.Range(0, searchSetting.IndustryIds.Length).Select(i => { if (searchSetting.IndustryIds[i] > 0) { return(string.Format(" A2C.CategoryId = {0} ", searchSetting.IndustryIds[i])); } return(string.Empty); }).Aggregate((a, b) => a + " OR " + b); if (!string.IsNullOrEmpty(temp)) { sbSQL.Append(" AND EXISTS("); sbSQL.Append(" SELECT * FROM dbo.Article2Category AS A2C WITH(NOLOCK)"); sbSQL.Append(" WHERE A2C.[Type] = 'industry'"); sbSQL.Append(" AND A.Id = A2C.ArticleId"); sbSQL.AppendFormat(" AND ( {0} )", temp); sbSQL.Append(" )"); } } if (!searchSetting.IsDeleted) { sbSQL.Append(" AND IsDeleted = 0"); } fp.Condition = " 1 = 1 " + sbSQL.ToString(); //throw new Exception(fp.Build2005()); IList <ArticleInfo> list = new List <ArticleInfo>(); ArticleInfo model = null; DataTable dt = SQLPlus.ExecuteDataTable(CommandType.Text, fp.Build2005()); if (dt != null && dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { model = GetByDataRow(dr); if (model != null) { list.Add(model); } } } int count = Convert.ToInt32(SQLPlus.ExecuteScalar(CommandType.Text, fp.BuildCountSQL())); return(new PageOfList <ArticleInfo>(list, searchSetting.PageIndex, searchSetting.PageSize, count)); }
public void TestSchemaTable() { DataSet ds = new DataSet(); DataTable testTable = new DataTable ("TestTable1"); DataTable testTable1 = new DataTable (); testTable.Namespace = "TableNamespace"; testTable1.Columns.Add ("col1", typeof(int)); testTable1.Columns.Add ("col2", typeof(int)); ds.Tables.Add (testTable); ds.Tables.Add (testTable1); //create a col for standard datatype testTable.Columns.Add ("col_string"); testTable.Columns.Add ("col_string_fixed"); testTable.Columns ["col_string_fixed"].MaxLength = 10; testTable.Columns.Add ("col_int", typeof(int)); testTable.Columns.Add ("col_decimal", typeof(decimal)); testTable.Columns.Add ("col_datetime", typeof(DateTime)); testTable.Columns.Add ("col_float", typeof (float)); // Check for col constraints/properties testTable.Columns.Add ("col_readonly").ReadOnly = true; testTable.Columns.Add ("col_autoincrement", typeof(Int64)).AutoIncrement = true; testTable.Columns ["col_autoincrement"].AutoIncrementStep = 5; testTable.Columns ["col_autoincrement"].AutoIncrementSeed = 10; testTable.Columns.Add ("col_pk"); testTable.PrimaryKey = new DataColumn[] {testTable.Columns ["col_pk"]}; testTable.Columns.Add ("col_unique"); testTable.Columns ["col_unique"].Unique = true; testTable.Columns.Add ("col_defaultvalue"); testTable.Columns ["col_defaultvalue"].DefaultValue = "DefaultValue"; testTable.Columns.Add ("col_expression_local", typeof(int)); testTable.Columns ["col_expression_local"].Expression = "col_int*5"; ds.Relations.Add ("rel", new DataColumn[] {testTable1.Columns ["col1"]}, new DataColumn[] {testTable.Columns ["col_int"]}, false); testTable.Columns.Add ("col_expression_ext"); testTable.Columns ["col_expression_ext"].Expression = "parent.col2"; testTable.Columns.Add ("col_namespace"); testTable.Columns ["col_namespace"].Namespace = "ColumnNamespace"; testTable.Columns.Add ("col_mapping"); testTable.Columns ["col_mapping"].ColumnMapping = MappingType.Attribute; DataTable schemaTable = testTable.CreateDataReader ().GetSchemaTable (); Assert.AreEqual (25, schemaTable.Columns.Count, "#1"); Assert.AreEqual (testTable.Columns.Count, schemaTable.Rows.Count, "#2"); //True for all rows for (int i = 0; i < schemaTable.Rows.Count; ++i) { Assert.AreEqual (testTable.TableName, schemaTable.Rows [i]["BaseTableName"], i+"_#3"); Assert.AreEqual (ds.DataSetName, schemaTable.Rows [i]["BaseCatalogName"], i+"_#4"); Assert.AreEqual (DBNull.Value, schemaTable.Rows [i]["BaseSchemaName"], i+"_#5"); Assert.AreEqual (schemaTable.Rows [i]["BaseColumnName"], schemaTable.Rows [i]["ColumnName"], i+"_#6"); Assert.IsFalse ((bool)schemaTable.Rows [i]["IsRowVersion"], i+"_#7"); } Assert.AreEqual ("col_string", schemaTable.Rows [0]["ColumnName"], "#8"); Assert.AreEqual (typeof(string), schemaTable.Rows [0]["DataType"], "#9"); Assert.AreEqual (-1, schemaTable.Rows [0]["ColumnSize"], "#10"); Assert.AreEqual (0, schemaTable.Rows [0]["ColumnOrdinal"], "#11"); // ms.net contradicts documented behavior Assert.IsFalse ((bool)schemaTable.Rows [0]["IsLong"], "#12"); Assert.AreEqual ("col_string_fixed", schemaTable.Rows [1]["ColumnName"], "#13"); Assert.AreEqual (typeof(string), schemaTable.Rows [1]["DataType"], "#14"); Assert.AreEqual (10, schemaTable.Rows [1]["ColumnSize"], "#15"); Assert.AreEqual (1, schemaTable.Rows [1]["ColumnOrdinal"], "#16"); Assert.IsFalse ((bool)schemaTable.Rows [1]["IsLong"], "#17"); Assert.AreEqual ("col_int", schemaTable.Rows [2]["ColumnName"], "#18"); Assert.AreEqual (typeof(int), schemaTable.Rows [2]["DataType"], "#19"); Assert.AreEqual (DBNull.Value, schemaTable.Rows [2]["NumericPrecision"], "#20"); Assert.AreEqual (DBNull.Value, schemaTable.Rows [2]["NumericScale"], "#21"); Assert.AreEqual (-1, schemaTable.Rows [2]["ColumnSize"], "#22"); Assert.AreEqual (2, schemaTable.Rows [2]["ColumnOrdinal"], "#23"); Assert.AreEqual ("col_decimal", schemaTable.Rows [3]["ColumnName"], "#24"); Assert.AreEqual (typeof(decimal), schemaTable.Rows [3]["DataType"], "#25"); // When are the Precision and Scale Values set ? Assert.AreEqual (DBNull.Value, schemaTable.Rows [3]["NumericPrecision"], "#26"); Assert.AreEqual (DBNull.Value, schemaTable.Rows [3]["NumericScale"], "#27"); Assert.AreEqual (-1, schemaTable.Rows [3]["ColumnSize"], "#28"); Assert.AreEqual (3, schemaTable.Rows [3]["ColumnOrdinal"], "#29"); Assert.AreEqual ("col_datetime", schemaTable.Rows [4]["ColumnName"], "#30"); Assert.AreEqual (typeof(DateTime), schemaTable.Rows [4]["DataType"], "#31"); Assert.AreEqual (4, schemaTable.Rows [4]["ColumnOrdinal"], "#32"); Assert.AreEqual ("col_float", schemaTable.Rows [5]["ColumnName"], "#33"); Assert.AreEqual (typeof(float), schemaTable.Rows [5]["DataType"], "#34"); Assert.AreEqual (5, schemaTable.Rows [5]["ColumnOrdinal"], "#35"); Assert.AreEqual (DBNull.Value, schemaTable.Rows [5]["NumericPrecision"], "#36"); Assert.AreEqual (DBNull.Value, schemaTable.Rows [5]["NumericScale"], "#37"); Assert.AreEqual (-1, schemaTable.Rows [5]["ColumnSize"], "#38"); Assert.AreEqual ("col_readonly", schemaTable.Rows [6]["ColumnName"], "#39"); Assert.IsTrue ((bool)schemaTable.Rows [6]["IsReadOnly"], "#40"); Assert.AreEqual ("col_autoincrement", schemaTable.Rows [7]["ColumnName"], "#9"); Assert.IsTrue ((bool)schemaTable.Rows [7]["IsAutoIncrement"], "#41"); Assert.AreEqual (10, schemaTable.Rows [7]["AutoIncrementSeed"], "#42"); Assert.AreEqual (5, schemaTable.Rows [7]["AutoIncrementStep"], "#43"); Assert.IsFalse ((bool)schemaTable.Rows [7]["IsReadOnly"], "#44"); Assert.AreEqual ("col_pk", schemaTable.Rows [8]["ColumnName"], "#45"); Assert.IsTrue ((bool)schemaTable.Rows [8]["IsKey"], "#46"); Assert.IsTrue ((bool)schemaTable.Rows [8]["IsUnique"], "#47"); Assert.AreEqual ("col_unique", schemaTable.Rows [9]["ColumnName"], "#48"); Assert.IsTrue ((bool)schemaTable.Rows [9]["IsUnique"], "#49"); Assert.AreEqual ("col_defaultvalue", schemaTable.Rows [10]["ColumnName"], "#50"); Assert.AreEqual ("DefaultValue", schemaTable.Rows [10]["DefaultValue"], "#51"); Assert.AreEqual ("col_expression_local", schemaTable.Rows [11]["ColumnName"], "#52"); Assert.AreEqual ("col_int*5", schemaTable.Rows [11]["Expression"], "#53"); Assert.IsTrue ((bool)schemaTable.Rows [11]["IsReadOnly"], "#54"); // if expression depends on a external col, then set Expression as null.. Assert.AreEqual ("col_expression_ext", schemaTable.Rows [12]["ColumnName"], "#55"); Assert.AreEqual (DBNull.Value, schemaTable.Rows [12]["Expression"], "#56"); Assert.IsTrue ((bool)schemaTable.Rows [12]["IsReadOnly"], "#57"); Assert.AreEqual ("col_namespace", schemaTable.Rows [13]["ColumnName"], "#58"); Assert.AreEqual ("TableNamespace", schemaTable.Rows [13]["BaseTableNamespace"], "#59"); Assert.AreEqual ("TableNamespace", schemaTable.Rows [12]["BaseColumnNamespace"], "#60"); Assert.AreEqual ("ColumnNamespace", schemaTable.Rows [13]["BaseColumnNamespace"], "#61"); Assert.AreEqual ("col_mapping", schemaTable.Rows [14]["ColumnName"], "#62"); Assert.AreEqual (MappingType.Element, (MappingType)schemaTable.Rows [13]["ColumnMapping"], "#63"); Assert.AreEqual (MappingType.Attribute, (MappingType)schemaTable.Rows [14]["ColumnMapping"], "#64"); }
protected void Page_Load(object sender, EventArgs e) { try { if (Session["ReportData"] != null) { string rptFullPath = Server.MapPath(@"..\Reports\RptFiles\MD_Prio_cost\rptIntersectMaintenancePriority.rpt"); DataTable dt = (DataTable)Session["ReportData"]; ReportDocument rpt = new ReportDocument(); rpt.Load(rptFullPath); rpt.SetDataSource(dt); Session.Remove("ReportData"); MemoryStream memStream; Response.Buffer = false; Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); if (Request.QueryString["type"] == "x") { ExcelFormatOptions excelOptions = new ExcelFormatOptions(); excelOptions.ExcelUseConstantColumnWidth = false; rpt.ExportOptions.FormatOptions = excelOptions; memStream = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.ExcelRecord); Response.ContentType = "application/vnd.ms-excel"; } else { memStream = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); Response.ContentType = "application/pdf"; //memStream = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.WordForWindows); //Response.ContentType = "application/msword"; } Response.BinaryWrite(memStream.ToArray()); Response.End(); memStream.Flush(); memStream.Close(); memStream.Dispose(); rpt.Close(); rpt.Dispose(); GC.Collect(); } else Response.Redirect("IntersectMaintenancePriorities.aspx", false); } catch (Exception ex) { Response.Write(ex.Message); } finally { Session["ReportData"] = null; } }
protected void register_Click(object sender, EventArgs e) { string name1 = name.Text.Trim(); string uname = usersname.Text.Trim(); string pwd1 = pwd.Text.Trim(); string sex1 = sex.SelectedValue; string tel1 = tel.Text.Trim(); string birth1 = birth.Text.Trim(); string blood1 = blood.Text.Trim(); string qzone = qzonename.Text.Trim(); string email1 = email.Text.Trim(); string validatecode = validate.Text.Trim(); string filename = ""; Boolean fileOK = false; if (upload.HasFile)//判断是否已选取文件 { String fileExtension = System.IO.Path.GetExtension(upload.FileName).ToLower(); //取得文件的扩展名 String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };//限定上传文件类型为这几种类型 for (int i = 0; i < allowedExtensions.Length; i++) { if (fileExtension == allowedExtensions[i]) //判断文件的类型是否为图片类型一个个匹对 { fileOK = true; } } } sqlh.FileExtension[] fe = { sqlh.FileExtension.BMP, sqlh.FileExtension.GIF, sqlh.FileExtension.JPG, sqlh.FileExtension.PNG }; if (name1.Length > 0 && uname.Length > 0 && pwd1.Length > 0 && sex1.Length > 0 && tel1.Length > 0 && birth1.Length > 0 && blood1.Length > 0 && email1.Length > 0) { if (validatecode == Session["vcode"].ToString()) //验证码是否正确 { string sqlname = "select * from Users where Name=@name"; //查找用户名是否存在 SqlParameter[] pname = { new SqlParameter("@name", name1) }; DataTable dt = sqlh.sqlselect(sqlname, pname); string sqltel = "select * from Users where Telephone=@tel"; //查找手机号是否存在 SqlParameter[] ptel = { new SqlParameter("@tel", tel1) }; DataTable dt2 = sqlh.sqlselect(sqltel, ptel); string sqlemail = "select * from Users where Email=@email"; //查找邮箱是否存在 SqlParameter[] pemail = { new SqlParameter("@email", email1) }; DataTable dt1 = sqlh.sqlselect(sqlemail, pemail); if (dt.Rows.Count == 0) //如果用户名和邮箱和手机号都不存在 { if (dt1.Rows.Count == 0) { if (dt2.Rows.Count == 0) { if (fileOK && sqlh.FileValidation.IsAllowedExtension(upload, fe)) //判断文件类型是否为bmp/gif/jpg/png以及检测头文件 { string fileExt = System.IO.Path.GetExtension(upload.FileName).ToLower(); filename = "/PhotoFile/" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt; //设置文件名 upload.SaveAs(Server.MapPath(filename));//存储文件 string pwd2 = sqlh.MD5(pwd1);//密码加密 string sql = "insert into Users(Name,Password,UsersName,Sex,Telephone,Birthday,Blood,Email,QzoneName,State,Image) values(@name2,@pwd2,@uname2,@sex2,@tel2,@birth2,@blood2,@email2,@qzone,'0',@image)"; SqlParameter[] sqls = { new SqlParameter("@name2",name1), new SqlParameter("@pwd2",pwd2), new SqlParameter("@uname2",uname), new SqlParameter("@sex2",sex1), new SqlParameter("@tel2",tel1), new SqlParameter("@birth2",birth1), new SqlParameter("@blood2",blood1), new SqlParameter("@email2",email1), new SqlParameter("@qzone",qzone), new SqlParameter("@image",filename) }; //参数化处理 int result = sqlh.sqlhelper(sql, sqls); if (result > 0) { Session["name"] = name1; Session["email"] = email1; Response.Write("<script>alert('注册成功!');location='ValidateEmail.aspx'</script>"); Random ran = new Random(); int n = ran.Next(1000, 9999); //生成1000-9999的随机数 Response.Cookies["code1"].Value = n.ToString(); //设置邮箱中验证码的cookies Response.Cookies["code1"].Expires = DateTime.Now.AddMinutes(5); string totitle = "亲爱的,这里有封信件~"; string tobody = "亲爱的qq空间用户'" + name1 + "',欢迎注册,您的注册确认验证码为'" + n + "',请尽快确认噢,验证码在五分钟后失效"; try { sqlh.email(email1, totitle, tobody); //执行发送邮件 } catch { Response.Write("<script>alert('发送邮件失败请重试');location='/MyLogin.axpx'</script>"); } } else Response.Write("<script>alert('注册失败请重试')</script>"); } else Response.Write("<script>alert('图片类型不符!')</script>"); } else Response.Write("<script>alert('手机号已存在!')</script>"); } else Response.Write("<script>alert('邮箱已存在!')</script>"); } else Response.Write("<script>alert('用户名已存在!')</script>"); } else Response.Write("<script>alert('验证码输入错误!')</script>"); } else Response.Write("<script>alert('注册信息不能为空!')</script>"); }
static void Main(string[] args) { var data = new DataTable(); using (var csvReader = new CsvReader(new StreamReader(System.IO.File.OpenRead(@"data.csv")), false, ',')) { data.Load(csvReader); } object[] headers = (object[])data.Rows[0].ItemArray.Clone(); //foreach(var item in headers.ItemArray) Write(item + " "); WriteLine(); data.Rows[0].Delete(); data.AcceptChanges(); bool runprog = true; var drillaggregates = new List <int>(); headermenu(headers); Console.Write("Enter initial aggregate column # (must be numeric values only): "); var initagg = Convert.ToInt32(Console.ReadLine()); drillaggregates.Add(initagg); var filters = new List <int>(); var filterdata = new List <object>(); do { try { WriteLine("Menu options:\n\t0. Display Fact Table\n\t1. Display Aggregated Table\n\t2. Reinitialize Aggregate\n\t3. Drill-down\n\t4. Filter\n\t5. View\n\t6. Quit\n\t7. Reset Drill Aggregates\n\t8. Reset Filters\n\t9. Remove Drill Aggregate\n\t10.Remove Filter"); // also remove aggregate on website Write("Enter menu choice #: "); int menuoption = Convert.ToInt32(Console.ReadLine()); if (menuoption == 0) // Display Fact Table { var watch = Stopwatch.StartNew(); WriteLine(string.Join(",", headers)); for (int i = 0; i < data.Rows.Count; i++) { WriteLine(string.Join(", ", data.Rows[i].ItemArray)); } watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 1) // Display Aggregated Table { var watch = Stopwatch.StartNew(); displayaggregatetable(data, headers, drillaggregates.ToArray(), filters.ToArray(), filterdata.ToArray()); watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 2) // Reinitialize Aggregate { var watch = Stopwatch.StartNew(); headermenu(headers); Write("Enter initial aggregate column # (must be numeric values only): "); initagg = Convert.ToInt32(Console.ReadLine()); if (drillaggregates.Count == 0) { drillaggregates.Add(initagg); } else { drillaggregates[0] = initagg; } watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 3) // Drill-down { var watch = Stopwatch.StartNew(); headermenu(headers); Write("Enter drill-down aggregate choice #: "); int drillagg = Convert.ToInt32(Console.ReadLine()); if (!drillaggregates.Contains(drillagg)) { drillaggregates.Add(drillagg); } displayaggregatetable(data, headers, drillaggregates.ToArray(), filters.ToArray(), filterdata.ToArray()); watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 4) // Filter { var watch = Stopwatch.StartNew(); headermenu(headers); Write("Enter filter header choice #: "); int filterheader = Convert.ToInt32(Console.ReadLine()); var filteroptions = new List <object>(); for (int i = 0; i < data.Rows.Count; i++) { filteroptions.Add(data.Rows[i][filterheader]); } filteroptions = filteroptions.Distinct().ToList(); WriteLine("Filter options: "); for (int i = 0; i < filteroptions.Count; i++) { WriteLine("\t{0}. {1}", i, filteroptions[i]); } Write("Enter filter option choice #: "); int filterby = Convert.ToInt32(Console.ReadLine()); var filter = filteroptions[filterby]; if (!filters.Contains(filterheader)) { filters.Add(filterheader); filterdata.Add(filter); } if (drillaggregates.Count > 1 || filters.Count > 0) { displayaggregatetable(data, headers, drillaggregates.ToArray(), filters.ToArray(), filterdata.ToArray()); } else { if (filters.Count == 0 && drillaggregates.Count == 1) { var filtertable = data.Clone(); for (int i = 0; i < filtertable.Rows.Count; i++) { if (filtertable.Rows[i][filterheader] != filter) { filtertable.Rows[i].Delete(); } } filtertable.AcceptChanges(); WriteLine(string.Join(",", headers)); for (int i = 0; i < filtertable.Rows.Count; i++) { WriteLine(string.Join(", ", filtertable.Rows[i].ItemArray)); } } } watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 5) // View { var watch = Stopwatch.StartNew(); DataTable x, y; int xhead, yhead; if (filters.Count == 0 && drillaggregates.Count == 1) { headermenu(headers); Write("Enter x header column #: "); xhead = Convert.ToInt32(Console.ReadLine()); Write("Enter y header column #: "); yhead = Convert.ToInt32(Console.ReadLine()); x = data.Copy(); y = data.Copy(); for (int i = data.Columns.Count; i-- > 0;) { if (i != xhead) { x.Columns.RemoveAt(i); } if (i != yhead) { y.Columns.RemoveAt(i); } } } else { WriteLine("Header options (remove drill aggregates to display more options):"); for (int i = 0; i < drillaggregates.Count; i++) { WriteLine("{0}. {1}", drillaggregates[i], headers[drillaggregates[i]]); } Write("Enter x header column #: "); xhead = Convert.ToInt32(Console.ReadLine()); Write("Enter y header column #: "); yhead = Convert.ToInt32(Console.ReadLine()); var sorteddrillagg = drillaggregates.ToArray(); Array.Sort(sorteddrillagg); int xheadind = Array.IndexOf(sorteddrillagg, xhead); int yheadind = Array.IndexOf(sorteddrillagg, yhead); x = getaggregatetable(data, drillaggregates.ToArray(), filters.ToArray(), filterdata.ToArray()); for (int i = x.Columns.Count; i-- > 0;) { if (i != xheadind) { x.Columns.RemoveAt(i); } } y = getaggregatetable(data, drillaggregates.ToArray(), filters.ToArray(), filterdata.ToArray()); for (int i = y.Columns.Count; i-- > 0;) { if (i != yheadind) { y.Columns.RemoveAt(i); } } } WriteLine("Graph options:\n\t1. Bar\n\t2. Line\n\t3. Line with Marker\n\t4. Scatter\n\t5. Pie"); Write("Enter graph choice #: "); int graphtype = Convert.ToInt32(Console.ReadLine()); var xlist = new List <object>(); var ylist = new List <object>(); for (int i = 0; i < x.Rows.Count; i++) { xlist.Add(x.Rows[i][0]); ylist.Add(y.Rows[i][0]); } var myModel = new PlotModel { Title = $"Data from the CSV File: {headers[xhead]} and {headers[yhead]}", Background = OxyColors.White }; var linearAxis1 = new LinearAxis(); linearAxis1.Position = AxisPosition.Bottom; var linearAxis2 = new LinearAxis(); linearAxis2.Position = AxisPosition.Left; if (graphtype != 5 || graphtype != 1) { linearAxis1.Title = headers[xhead].ToString(); linearAxis2.Title = headers[yhead].ToString(); } // else { linearAxis1.Title = headers[xhead].ToString(); } if (graphtype != 1) { myModel.Axes.Add(linearAxis1); } if (graphtype != 1) { myModel.Axes.Add(linearAxis2); } if (graphtype == 1) // Bar { var barSource = new List <BarItem>(); for (int i = 0; i < xlist.Count; i++) { barSource.Add(new BarItem { Value = Convert.ToDouble(ylist[i]) }); } var barSeries = new BarSeries { ItemsSource = barSource, LabelPlacement = LabelPlacement.Inside, }; var catSource = new List <string>(); for (int i = 0; i < xlist.Count; i++) { catSource.Add(xlist[i].ToString()); } linearAxis1.Title = headers[yhead].ToString(); myModel.Series.Add(barSeries); myModel.Axes.Add(new CategoryAxis { Position = AxisPosition.Left, Key = "X_Axis", Title = headers[xhead].ToString(), ItemsSource = catSource.ToArray() }); myModel.Axes.Add(linearAxis1); } else if (graphtype == 2) // Line { var lineSeries = new LineSeries(); for (int i = 0; i < xlist.Count; i++) { lineSeries.Points.Add(new DataPoint(Convert.ToDouble(xlist[i]), Convert.ToDouble(ylist[i]))); } myModel.Series.Add(lineSeries); } else if (graphtype == 3) // Line with Marker { var lineSeries = new LineSeries(); lineSeries.MarkerType = MarkerType.Circle; lineSeries.MarkerSize = 5; lineSeries.MarkerStroke = OxyColors.Black; lineSeries.MarkerFill = OxyColors.SkyBlue; lineSeries.MarkerStrokeThickness = 1.5; for (int i = 0; i < xlist.Count; i++) { lineSeries.Points.Add(new DataPoint(Convert.ToDouble(xlist[i]), Convert.ToDouble(ylist[i]))); } myModel.Series.Add(lineSeries); } else if (graphtype == 4) // Scatter { var scatterSeries = new ScatterSeries(); for (int i = 0; i < xlist.Count; i++) { scatterSeries.Points.Add(new ScatterPoint(Convert.ToDouble(xlist[i]), Convert.ToDouble(ylist[i]))); } myModel.Series.Add(scatterSeries); } else if (graphtype == 5) // Pie { var aggr_x = xlist.Distinct().ToList(); //plt.pie(aggr_x, labels=aggr_x) var pieSeries = new PieSeries { StrokeThickness = 2.0, InsideLabelPosition = 0.8, AngleSpan = 360, StartAngle = 0 }; for (int i = 0; i < xlist.Count; i++) { pieSeries.Slices.Add(new PieSlice(xlist[i].ToString(), Convert.ToDouble(ylist[i])) { IsExploded = false }); } myModel.Series.Add(pieSeries); //https://oxyplot.readthedocs.io/en/latest/models/series/PieSeries.html } var form = new Form1(myModel); Application.EnableVisualStyles(); Application.Run(form); var stream = new MemoryStream(); var pngExporter = new PngExporter { Width = 600, Height = 400 }; //, Background = OxyColors.White }; pngExporter.Export(myModel, stream); var bytes = new Byte[(int)stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(bytes, 0, (int)stream.Length); string b64 = Convert.ToBase64String(bytes); string uri = "data:image/png;base64," + b64; string html = $"<img src = \"{uri}\"/>"; watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 6) // Quit { runprog = false; return; } else if (menuoption == 7) // Reset Drill Aggregates { var watch = Stopwatch.StartNew(); drillaggregates.Clear(); watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 8) // Reset Filters { var watch = Stopwatch.StartNew(); filters.Clear(); filterdata.Clear(); watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 9) // Remove Drill Aggregate { var watch = Stopwatch.StartNew(); WriteLine("Current drill aggregates:"); for (int i = 0; i < drillaggregates.Count; i++) { WriteLine("{0}. {1}", i, headers[drillaggregates[i]]); } Write("Enter choice # to remove: "); int removechoice = Convert.ToInt32(Console.ReadLine()); drillaggregates.RemoveAt(removechoice); watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } else if (menuoption == 10) // Remove Filter { var watch = Stopwatch.StartNew(); WriteLine("Current filters:"); for (int i = 0; i < filters.Count; i++) { WriteLine("{0}. {1}", i, headers[filters[i]]); } Write("Enter choice # to remove: "); int removechoice = Convert.ToInt32(Console.ReadLine()); filters.RemoveAt(removechoice); filterdata.RemoveAt(removechoice); watch.Stop(); WriteLine("Execution time in seconds: {0}", watch.Elapsed.TotalSeconds); } } catch (Exception ex) { WriteLine(ex.StackTrace); } } while (runprog); }
protected void bindGrid(int advisorBranchId, int branchHeadId, int all) { //DataSet ds = new DataSet(); //DataTable BranchAssetsTab = new DataTable(); DataRow drAssets; DataRow drValues; branchDetailsDS = advisorBranchBo.GetBranchAssets(advisorBranchId, branchHeadId, all); topFiveRMDT = branchDetailsDS.Tables[1]; topFiveCustomerDT = branchDetailsDS.Tables[2]; if (branchDetailsDS.Tables[0].Rows.Count > 0) { hrBranchAum.Visible = true; ErrorMessage.Visible = false; lblBranchAUM.Visible = true; branchAumDT.Columns.Add("Asset"); branchAumDT.Columns.Add("CurrentValue"); drValues = branchDetailsDS.Tables[0].Rows[0]; //DataView view = branchAumDT.DefaultView; //view.Sort = "CurrentValue"; for (int i = 0; i < branchDetailsDS.Tables[0].Columns.Count - 1; i++) { drAssets = branchAumDT.NewRow(); drAssets["Asset"] = branchDetailsDS.Tables[0].Columns[i].ColumnName; drAssets["CurrentValue"] = drValues[i].ToString(); branchAumDT.Rows.Add(drAssets); if (GridViewCultureFlag == true) { double tempCurrValue = 0; double.TryParse(drValues[i].ToString(), out tempCurrValue); tempCurrValue = Math.Round(tempCurrValue, 2); drAssets["CurrentValue"] = tempCurrValue.ToString("n2", System.Globalization.CultureInfo.CreateSpecificCulture("hi-IN")); } else { double tempCurrValue = 0; double.TryParse(drValues[i].ToString(), out tempCurrValue); tempCurrValue = Math.Round(tempCurrValue, 2); drAssets["CurrentValue"] = tempCurrValue; } } gvBMDashBoardGrid.DataSource = branchAumDT; //branchAumDT.DefaultView.Sort = "CurrentValue"; gvBMDashBoardGrid.DataBind(); gvBMDashBoardGrid.GridLines = GridLines.Both; Label TotalText = (Label)gvBMDashBoardGrid.FooterRow.FindControl("lblTotalText"); Label TotalValue = (Label)gvBMDashBoardGrid.FooterRow.FindControl("lblTotalValue"); TotalText.Text = branchDetailsDS.Tables[0].Columns[branchDetailsDS.Tables[0].Columns.Count - 1].ColumnName; TotalValue.Text = drValues[branchDetailsDS.Tables[0].Columns.Count - 1].ToString(); if (GridViewCultureFlag == true) { double tempTotalValue = 0; double.TryParse(drValues[branchDetailsDS.Tables[0].Columns.Count - 1].ToString(), out tempTotalValue); tempTotalValue = Math.Round(tempTotalValue, 2); TotalValue.Text = tempTotalValue.ToString("n2", System.Globalization.CultureInfo.CreateSpecificCulture("hi-IN")); } } else { hrBranchAum.Visible = false; ErrorMessage.Visible = true; gvBMDashBoardGrid.DataSource = null; gvBMDashBoardGrid.Visible = false; lblBranchAUM.Visible = false; } /* Top 5 RM Grid */ //DataRow drRMName; //DataRow drRMValue; //if (branchDetailsDS.Tables[0].Rows.Count > 0) //{ // hrTop5Rm.Visible = true; // ErrorMsgForTop5RMs.Visible = false; // lblTop5RM.Visible = true; //topFiveRMDT.Columns.Add("Rm Name"); //topFiveRMDT.Columns.Add("Staff Code"); //topFiveRMDT.Columns.Add("Customer base"); //topFiveRMDT.Columns.Add("Customer networth"); //drRMValue = branchDetailsDS.Tables[1].Rows[0]; //for (int i = 0; i < branchDetailsDS.Tables[1].Columns.Count; i++) //{ // drRMName = topFiveRMDT.NewRow(); // drRMName["RmName"] = branchDetailsDS.Tables[1].Columns[i].ColumnName; // drRMName["Staff_Code"] = branchDetailsDS.Tables[1].Columns[i].ColumnName; // drRMName["Customer_base"] = branchDetailsDS.Tables[1].Columns[i].ColumnName; // drRMName["Customer_networth"] = drRMValue[i].ToString(); // topFiveRMDT.Rows.Add(drRMName); // //if (GridViewCultureFlag == true) // //{ // // decimal tempRMValue = System.Math.Round(decimal.Parse(drRMValue[i].ToString()), 2); // // drRMName["Customer networth"] = tempRMValue.ToString("n2", System.Globalization.CultureInfo.CreateSpecificCulture("hi-IN")); // //} // //else // //{ // // drRMName["Customer networth"] = decimal.Parse(drRMValue[i].ToString()); // //} //} if (topFiveRMDT.Rows.Count > 0) { int i = 0; hrTop5Rm.Visible = true; ErrorMsgForTop5RMs.Visible = false; lblTop5RM.Visible = true; gvRMCustNetworth.Visible = true; for (i = 0; i < topFiveRMDT.Rows.Count - 1; i++) { topFiveRMDT.Rows[i]["Customer_networth"] = topFiveRMDT.Rows[i]["Customer_networth"].ToString(); } //if (GridViewCultureFlag == true) //{ // decimal tempRMValue = System.Math.Round(decimal.Parse(topFiveRMDT.Rows[i]["Customer_networth"].ToString()), 2); // topFiveRMDT.Rows[i]["Customer_networth"] = tempRMValue.ToString("n2", System.Globalization.CultureInfo.CreateSpecificCulture("hi-IN")); //} gvRMCustNetworth.DataSource = topFiveRMDT; gvRMCustNetworth.DataBind(); } else { hrTop5Rm.Visible = false; ErrorMsgForTop5RMs.Visible = true; lblTop5RM.Visible = false; gvRMCustNetworth.DataSource = null; gvRMCustNetworth.Visible = false; } if (topFiveCustomerDT.Rows.Count > 0) { hrTop5Cust.Visible = true; ErrorMsgForTop5Customer.Visible = false; gvCustNetWorth.Visible = true; lblTop5CustNetworth.Visible = true; gvCustNetWorth.DataSource = topFiveCustomerDT; gvCustNetWorth.DataBind(); } else { hrTop5Cust.Visible = false; ErrorMsgForTop5Customer.Visible = true; lblTop5CustNetworth.Visible = false; gvCustNetWorth.DataSource = null; gvCustNetWorth.Visible = false; } }
public ActionResult Edit_Admin_Menu() { this.Response.ContentType = "text/plain"; string level = this.Request.Form["level"];//0顶级1下一级 string menu_cc = this.Request.Form["menu_cc"]; byte bLevel = 0; byte.TryParse(level, out bLevel); NModel.Admin_Menu model = new NModel.Admin_Menu(); BLL.Admin_Menu dal = new BLL.Admin_Menu(); String JsonStr = ""; bool isGet = Tool.NStr.PostForSetVal<NModel.Admin_Menu>(ref model, ref JsonStr, ""); // 下面代码编写 && !string.IsNullOrEmpty(model.Menu_Img_url) if (isGet && model != null && !string.IsNullOrEmpty(model.Menu_Name) && model.Menu_X != null && model.Menu_X > 0 && model.Menu_Y > 0 && model.Menu_Z > 0 ) { string Xstr = (model.Menu_X + ""); long xOutLong = 0; long? zOutLong = 0; long yOutLong = 0; long? xLong = 0; DataTable dtMax = null; if (bLevel == 0) { if (model.Menu_Y == 1 && model.Menu_Z == 1) { dtMax = dal.GetFristLevelMaxXModel(); if (dtMax != null && dtMax.Rows.Count > 0) { long.TryParse(dtMax.Rows[0]["next_x"] + "", out xOutLong); model.Menu_X = xOutLong; } else { xOutLong = 1; yOutLong = 1; zOutLong = 1; } } else if (model.Menu_Z >= 2) { NModel.Admin_Menu nadm = dal.GetMaxXANDZYModel(model.Menu_X, model.Menu_Z); model.Menu_Y = (long)(nadm.Menu_Y + 1); } } else if (bLevel == 1) { string xStr = (model.Menu_X + ""); xStr = xStr.Replace("-", ""); long eqStr = 0; if (model.Menu_Z >= 2) { long.TryParse(string.Format("{0}{1}", xStr, model.Menu_Y), out eqStr); } else { long.TryParse(xStr + "", out eqStr); } dtMax = dal.GetXMaxYModel(eqStr); if (dtMax != null && dtMax.Rows.Count > 0) { long.TryParse(dtMax.Rows[0]["next_y"] + "", out yOutLong); } else { yOutLong = 1; } xOutLong = eqStr; zOutLong = model.Menu_Z + 1; model.Menu_X = xOutLong; model.Menu_Y = yOutLong > 0 ? yOutLong : 1; model.Menu_Z = zOutLong; } else if (bLevel == 0) { xLong = xOutLong = model.Menu_X != null ? Convert.ToInt64(model.Menu_X) : 1; if (model.Menu_Y == 1 && model.Menu_Z == 1) { model.Menu_X = xOutLong; model.Menu_Y = yOutLong > 0 ? yOutLong : 1; model.Menu_Z = zOutLong; } dtMax = dal.GetXMaxYModel(model.Menu_X); if (dtMax != null && dtMax.Rows.Count > 0) { long.TryParse(dtMax.Rows[0]["next_y"] + "", out yOutLong); } zOutLong = model.Menu_Z; } model.Menu_EditTime = DateTime.Parse(DateTime.Now.ToString("s")); bool isEdit = dal.Edit(model) > 0 ? true : false; if (isEdit) { this.Response.Write(Tool.NMsg.SetMsg("修改成功", "1")); this.Response.End(); } else { this.Response.Write(Tool.NMsg.SetMsg("修改失败", "0")); this.Response.End(); } } else { this.Response.Write(Tool.NMsg.SetMsg("提交失败/填写数据不完整", "0")); this.Response.End(); } dal.Close(); return View(); }
public ActionResult Move_Admin_Menu() { string delList = this.Request.Form["delList[]"]; string name = this.Request.Form["id"]; string _nlevel = this.Request.Form["nlevel"]; long x = 0, y = 0, z = 0, nlevel; long.TryParse(_nlevel, out nlevel); if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(delList)) { string[] arrStr = delList.Split(','); int[] delIntArr = Tool.NTool.ArrayToAll<int, string>(arrStr); if (Tool.NTool.IsArrNULL<int>(delIntArr)) { long long_Result = 0; BLL.Admin_Menu dal = new BLL.Admin_Menu(); long num = long.Parse(name); NModel.Admin_Menu model = dal.GetModel(((long?)num)); DataTable dtMax = null; if (model != null) { switch (nlevel) { case 0: { if (model.Menu_Y == 1 && model.Menu_Z == 1) { dtMax = dal.GetFristLevelMaxXModel(); if (dtMax != null && dtMax.Rows.Count > 0) { long.TryParse(dtMax.Rows[0]["next_x"] + "", out x); y = (long)model.Menu_Y; z = (long)model.Menu_Z; } else { x = 1; y = 1; z = 1; } } else if (model.Menu_Z >= 2) { NModel.Admin_Menu nadm = dal.GetMaxXANDZYModel(model.Menu_X, model.Menu_Z); y = (long)(nadm.Menu_Y + 1); } } break; case 1: { string xStr = (model.Menu_X + ""); xStr = xStr.Replace("-", ""); long eqStr = 0; if (model.Menu_Z >= 2) { long.TryParse(string.Format("{0}{1}", xStr, model.Menu_Y), out eqStr); } else { long.TryParse(xStr + "", out eqStr); } dtMax = dal.GetXMaxYModel(eqStr); if (dtMax != null && dtMax.Rows.Count > 0) { long.TryParse(dtMax.Rows[0]["next_y"] + "", out y); } else { y = 1; } x = eqStr; z = (long)model.Menu_Z + 1; y = y > 0 ? y : 1; } break; } for (int i = 0; i < delIntArr.Length; i++) { long? _id = delIntArr[i]; NModel.Admin_Menu mdl = dal.GetModel(_id); if (model.Menu_X == mdl.Menu_X && model.Menu_Y == mdl.Menu_Y && model.Menu_Z == mdl.Menu_Z ) { continue; } long _x = 0, _y = 0; if (z > 1) { _x = x; _y = y + i; } else { _x = x + i; _y = y; } long_Result += dal.EditFree(delIntArr[i], string.Format("Menu_X={0},Menu_Y={1},Menu_Z={2}", _x, _y, z)); } } if (long_Result > 0) { this.Response.Write(Tool.NMsg.SetMsg(string.Format("移动成功!总共{0}条", long_Result), "1")); this.Response.End(); } else { this.Response.Write(Tool.NMsg.SetMsg("移动失败!您输入分类名称不存在!", "0")); this.Response.End(); } dal.Close(); } else { this.Response.Write(Tool.NMsg.SetMsg("提交失败/填写数据不完整!", "0")); this.Response.End(); } } else { this.Response.Write(Tool.NMsg.SetMsg("提交失败/填写数据不完整!", "0")); this.Response.End(); } return View(); }
/// <summary> /// 分组查询历史记录月 /// </summary> /// <param name="Year"></param> /// <returns></returns> public DataTable Month(string Year) { DataTable dt = SQLHelp.ExecuteDataTable(" exec Proc_Month '" + Year + "'", CommandType.StoredProcedure, null); return(dt); }
public string ToString(DataTable table) { string jsonString = ConvertHelper.ToJson(table); return jsonString; }
/// <summary> /// 添加投屏信息 /// </summary> /// <param name="ComputerID"></param> /// <param name="UserName"></param> /// <returns></returns> public DataTable InProjectors(string ComputerID, string UserName) { DataTable dt = SQLHelp.ExecuteDataTable(" exec Proc_InProjectors '" + ComputerID + "','" + UserName + "'", CommandType.StoredProcedure, null); return(dt); }
/// <summary> /// 分组查询历史记录年 /// </summary> /// <returns></returns> public DataTable Year() { DataTable dt = SQLHelp.ExecuteDataTable(" exec Proc_Year", CommandType.StoredProcedure, null); return(dt); }
/// <summary> /// 获取总记录数 /// </summary> /// <returns></returns> public DataTable CountProjector() { DataTable dt = SQLHelp.ExecuteDataTable("exec PROC_CountProjector", CommandType.StoredProcedure, null); return(dt); }
/// <summary> /// 钉钉登陆判断账号所属 /// </summary> /// <param name="Name"></param> /// <param name="Phone"></param> /// <returns></returns> public DataTable getUserInfo(string Name, string Phone) { DataTable dt = SQLHelp.ExecuteDataTable(" select * from UserInfo where Name='" + Name + "' and Phone='" + Phone + "' ", CommandType.Text, null); return(dt); }
private void flgview_Patient_SelChange(object sender, EventArgs e) { try { flgView_Yb.Clear(); flgView_Gm.Clear(); mzh = flgview_Patient[flgview_Patient.RowSel, "住院号"].ToString(); yblsh = flgview_Patient[flgview_Patient.RowSel, "标本流水号"].ToString(); jyxmdm = flgview_Patient[flgview_Patient.RowSel, "检验项目代码"].ToString(); //if (jyxmdm == "") //{ // Sql_A = "select xmdm as 项目代码,xmmc as 项目名称,xmywmc as 项目英文名称,xmjg as 项目结果,jgdw as 单位,ckz as 参考值范围,cssj as 报告时间,jgbz as 标志 from t_lis_result where bblsh='" + yblsh + "' and yzxmdm is null order by xmjg asc"; //} //else //{ // Sql_A = "select xmdm as 项目代码,xmmc as 项目名称,xmywmc as 项目英文名称,xmjg as 项目结果,jgdw as 单位,ckz as 参考值范围,cssj as 报告时间,jgbz as 标志 from t_lis_result where bblsh='" + yblsh + "' and yzxmdm='" + jyxmdm + "' order by xmjg asc"; //} //if (jyxmdm == "") //{ // Sql_A = "select test_no as 项目代码,REPORT_ITEM_NAME as 项目名称,'' as 项目英文名称,RESULT as 项目结果,UNITS as 单位,PRINT_CONTEXT as 参考值范围,RESULT_DATE_TIME as 测试时间,ABNORMAL_INDICATOR as 标志 from lab_result@dbhislink r where test_no='" + yblsh + "'"; //} //else //{ Sql_A = "select xmdm as 项目代码,xmmc as 项目名称,xmywmc as 项目英文名称,xmjg as 项目结果,jgdw as 单位,ckz as 参考值范围,cssj as 测试时间,jgbz as 标志 from t_lis_result where bblsh='" + yblsh + "'";// and yzxmdm='" + jyxmdm + "'"; //} DataTable dt = App.GetDataSet(Sql_A).Tables[0]; DataColumn dc = new DataColumn("dcSectFlag", typeof(bool)); dc.Caption = "选择标记"; dc.DefaultValue = false; dt.Columns.Add(dc); SetTableSelFlag(dt, yblsh, jyxmdm); flgView_Yb.DataSource = dt; flgView_Yb.Select(0, 0); flgView_Yb.Refresh(); flgView_Yb.Cols["项目代码"].Visible = false; flgView_Yb.Cols["项目英文名称"].Visible = false; for (int i = 0; i < flgView_Yb.Rows.Count; i++) { if (flgView_Yb.Rows[i]["标志"].ToString().ToUpper() == "L") { flgView_Yb.Rows[i].StyleNew.BackColor = Color.SkyBlue; } else if (flgView_Yb.Rows[i]["标志"].ToString().ToUpper() == "H") { flgView_Yb.Rows[i].StyleNew.BackColor = Color.Red; } if (flgView_Yb.Rows[i]["标志"].ToString().ToLower() == "低") { flgView_Yb.Rows[i]["项目结果"] = flgView_Yb.Rows[i]["项目结果"] + "↓"; flgView_Yb.Rows[i].StyleNew.BackColor = Color.SkyBlue; } else if (flgView_Yb.Rows[i]["标志"].ToString().ToLower() == "高") { flgView_Yb.Rows[i]["项目结果"] = flgView_Yb.Rows[i]["项目结果"] + "↑"; flgView_Yb.Rows[i].StyleNew.BackColor = Color.Red; } if (flgView_Yb.Rows[i]["项目结果"].ToString().ToLower() == "阴性") { flgView_Yb.Rows[i].StyleNew.BackColor = Color.SkyBlue; } else if (flgView_Yb.Rows[i]["项目结果"].ToString().ToLower() == "阳性") { flgView_Yb.Rows[i].StyleNew.BackColor = Color.OrangeRed; } } this.flgView_Yb.Focus(); flgview_Patient.AllowEditing = false; flgView_Yb.Cols["项目名称"].AllowEditing = false; flgView_Yb.Cols["项目结果"].AllowEditing = false; flgView_Yb.Cols["单位"].AllowEditing = false; flgView_Yb.Cols["参考值范围"].AllowEditing = false; flgView_Yb.Cols["报告时间"].AllowEditing = false; flgView_Yb.Cols["标志"].AllowEditing = false; flgView_Yb.Cols["dcSectFlag"].AllowEditing = true; } catch { //string sql = "select xmdm as 项目代码,xmmc as 项目名称,xmywmc as 项目英文名称,xmjg as 项目结果,jgdw as 单位,ckz as 参考值范围,cssj as 报告时间,jgbz as 标志 from t_lis_result where bblsh='" + yblsh + "' and yzxmdm is null order by xmjg asc"; //DataTable dt = App.GetDataSet(sql).Tables[0]; //flgView_Yb.DataSource = dt; //DataColumn dc = new DataColumn("dcSectFlag", typeof(bool)); //dc.Caption = "选择标记"; //dc.DefaultValue = false; //dt.Columns.Add(dc); //flgView_Yb.Cols["项目代码"].Visible = false; //flgView_Yb.Cols["项目英文名称"].Visible = false; } }
/// <summary> /// 新用户登陆时候自动注册账号 /// </summary> /// <param name="name"></param> /// <param name="phone"></param> /// <returns></returns> public DataTable InUserLog(string name, string phone) { DataTable dt = SQLHelp.ExecuteDataTable("exec PROC_InUserLog '" + name + "','" + phone + "'", CommandType.StoredProcedure, null); return(dt); }
public CommonData.ReturnCode SearchData(IDTO searchDto, out DataTable dtResult) { throw new NotImplementedException(); }
/// <summary> /// 获得公式功率值, /// 键为OrganizationID值、LevelCode值和字符串PowerValue的拼接, /// 值为公式功率值 /// </summary> /// <param name="organizationId"></param> /// <returns></returns> public IEnumerable<DataItem> GetFormulaPower(string organizationId,string sceneName) { DataTable sourceTable = GetFormulaPowerValues(organizationId); // 获得formula_power表值 IEnumerable<DataItem> result = ConvertToDataItems(sourceTable,sceneName); // 将表中功率值转换为键值对 return result; }
public override void GetData() { LogInfo.Log.Info("执行SAP1客户行主数据同步"); StringBuilder errMsg = new StringBuilder(); StringBuilder successMsg = new StringBuilder(); SQLHelper.ExecuteNonQuery(context.connStr, "DELETE FROM MAIN_CUSTOMER WHERE COMPANY IN(" + filter + ")"); DataTable mainsupplier = SQLHelper.ExecuteDataset(context.connStr, CommandType.Text, "SELECT COMPANY, CSR_ID, CSR_NAME, CSR_ABB,FINCODE, DEL_FLG, KNA1KUNNR, KNA1LAND1, KNA1NAME1, KNA1NAME2, KNA1SORTL, KNA1ADRNR, KNA1ERDAT, KNA1ERNAM, KNA1KONZS, KNA1KTOKD, KNA1LIFNR, KNA1LOEVM, KNA1SPERR, KNA1SPRAS, KNA1STCD1, KNA1VBUND, KNA1STCEG, KNA1ZZDESTINATION, KNA1ZZPREFECTURE, KNA1ZZCITY, KNA1ZZAREACODE, KNA1ZZBIZMINUNIT, KNA1ZZCONCLASS, KNA1ZZRACUSTTYPE, KNA1ZZDEVDATE, KNA1ZZGRINOUTFLG, KNA1ZZVKBUR, KNA1ZKAIPIAO, KNA1ZHUISHOU, KNA1ZZGSQSEC_CUST, ADRCDATE_FROM, ADRCNATION, ADRCDATE_TO, ADRCTITLE, ADRCNAME1, ADRCNAME2, ADRCNAME3,ADRCNAME4, ADRCNAME_CO, ADRCCITY1, ADRCPOST_CODE1, ADRCPO_BOX, ADRCTRANSPZONE, ADRCSTREET, ADRCHOUSE_NUM1, ADRCSTR_SUPPL1,ADRCSTR_SUPPL2, ADRCSTR_SUPPL3, ADRCLOCATION, ADRCBUILDING, ADRCFLOOR, ADRCROOMNUMBER, ADRCCOUNTRY, ADRCLANGU, ADRCREGION, ADRCSORT1, ADRCSORT2, ADRCTEL_NUMBER, ADRCFAX_NUMBER, KNB1BUKRS, KNB1PERNR, KNB1ERDAT, KNB1ERNAM, KNB1SPERR, KNB1LOEVM,KNB1AKONT, KNB1ZTERM, KNVVVKORG, KNVVVTWEG, KNVVSPART, KNVVERNAM, KNVVERDAT, KNVVLOEVM, KNVVKALKS, KNVVKONDA, KNVVINCO1, KNVVINCO2, KNVVVSBED, KNVVWAERS, KNVVZTERM, KNVVVWERK, KNBKBANKS, KNBKBANKL, KNBKBANKN, KNBKBKONT, KNBKBKREF, KNBKKOINH, KNVKNAMEV, KNVKNAME1, KNVKTELF1, BNKABANKA FROM MAIN_CUSTOMER WHERE COMPANY IN(" + filter + ")").Tables[0]; //向表中添加数据 DataRow dr; ConnectFile.connectState(filePath, "NisMail_UserName".ToAppSetting(), "NisMail_PWD".ToAppSetting()); using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8)) { string str = sr.ReadToEnd(); string[] strlist = str.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); for (int i = 1; i < strlist.Length; i++) { string[] strs = strlist[i].Split('\t'); if (strs.Length < 92) { errMsg.AppendLine("第" + (i + 1) + "行数据完整性异常"); errorCount++; continue; } if (!dic.ContainsKey(strs[59])) { errMsg.AppendLine(string.Format("第{0}行公司编码:{1}客户行编码:{2}客户行名称:{3}不存在于MAIN_COMPANY表中", (i + 1), strs[59], strs[0], strs[2])); errorCount++; continue; } //string key = dic[strs[47]] + strs[0]; dr = mainsupplier.NewRow(); dr["COMPANY"] = dic[strs[59]]; dr["CSR_ID"] = strs[0]; dr["CSR_NAME"] = strs[2]; dr["CSR_ABB"] = strs[4]; dr["FINCODE"] = strs[65]; dr["DEL_FLG"] = strs[63].ToUpper() == "X" ? 1 : 0; dr["KNA1KUNNR"] = strs[0]; dr["KNA1LAND1"] = strs[1]; dr["KNA1NAME1"] = strs[2]; dr["KNA1NAME2"] = strs[3]; dr["KNA1SORTL"] = strs[4]; dr["KNA1ADRNR"] = strs[5]; if (strs[6] != "") { if (strs[6].Length == 8) { dr["KNA1ERDAT"] = SplitDate(strs[6]);//date } else { dr["KNA1ERDAT"] = DBNull.Value; } } else { dr["KNA1ERDAT"] = DBNull.Value; } dr["KNA1ERNAM"] = strs[7]; dr["KNA1KONZS"] = strs[8]; dr["KNA1KTOKD"] = strs[9]; dr["KNA1LIFNR"] = strs[10]; dr["KNA1LOEVM"] = strs[11]; dr["KNA1SPERR"] = strs[12]; dr["KNA1SPRAS"] = strs[13]; dr["KNA1STCD1"] = strs[14]; dr["KNA1VBUND"] = strs[15]; dr["KNA1STCEG"] = strs[16]; dr["KNA1ZZDESTINATION"] = strs[17]; dr["KNA1ZZPREFECTURE"] = strs[18]; dr["KNA1ZZCITY"] = strs[19]; dr["KNA1ZZAREACODE"] = strs[20]; dr["KNA1ZZBIZMINUNIT"] = strs[21]; dr["KNA1ZZCONCLASS"] = strs[22]; dr["KNA1ZZRACUSTTYPE"] = strs[23]; dr["KNA1ZZDEVDATE"] = strs[24]; dr["KNA1ZZGRINOUTFLG"] = strs[25]; dr["KNA1ZZVKBUR"] = strs[26]; dr["KNA1ZKAIPIAO"] = strs[27]; dr["KNA1ZHUISHOU"] = strs[28]; dr["KNA1ZZGSQSEC_CUST"] = strs[29]; if (strs[30] != "") { if (strs[30].Length == 8) { dr["ADRCDATE_FROM"] = SplitDate(strs[30]);//date } else { dr["ADRCDATE_FROM"] = DBNull.Value; } } else { dr["ADRCDATE_FROM"] = DBNull.Value; } dr["ADRCNATION"] = strs[31]; if (strs[32] != "") { if (strs[32].Length == 8) { dr["ADRCDATE_TO"] = SplitDate(strs[32]);//date } else { dr["ADRCDATE_TO"] = DBNull.Value; } } else { dr["ADRCDATE_TO"] = DBNull.Value; } dr["ADRCTITLE"] = strs[33]; dr["ADRCNAME1"] = strs[34]; dr["ADRCNAME2"] = strs[35]; dr["ADRCNAME3"] = strs[36]; dr["ADRCNAME4"] = strs[37]; dr["ADRCNAME_CO"] = strs[38]; dr["ADRCCITY1"] = strs[39]; dr["ADRCPOST_CODE1"] = strs[40]; dr["ADRCPO_BOX"] = strs[41]; dr["ADRCTRANSPZONE"] = strs[42]; dr["ADRCSTREET"] = strs[43]; dr["ADRCHOUSE_NUM1"] = strs[44]; dr["ADRCSTR_SUPPL1"] = strs[45]; dr["ADRCSTR_SUPPL2"] = strs[46]; dr["ADRCSTR_SUPPL3"] = strs[47]; dr["ADRCLOCATION"] = strs[48]; dr["ADRCBUILDING"] = strs[49]; dr["ADRCFLOOR"] = strs[50]; dr["ADRCROOMNUMBER"] = strs[51]; dr["ADRCCOUNTRY"] = strs[52]; dr["ADRCLANGU"] = strs[53]; dr["ADRCREGION"] = strs[54]; dr["ADRCSORT1"] = strs[55]; dr["ADRCSORT2"] = strs[56]; dr["ADRCTEL_NUMBER"] = strs[57]; dr["ADRCFAX_NUMBER"] = strs[58]; dr["KNB1BUKRS"] = strs[59];//COMPANY dr["KNB1PERNR"] = strs[60]; if (strs[61] != "") { if (strs[61].Length == 8) { dr["KNB1ERDAT"] = SplitDate(strs[61]);//date } else { dr["KNB1ERDAT"] = DBNull.Value; } } else { dr["KNB1ERDAT"] = DBNull.Value; } dr["KNB1ERNAM"] = strs[62]; dr["KNB1SPERR"] = strs[63]; dr["KNB1LOEVM"] = strs[64]; dr["KNB1AKONT"] = strs[65]; dr["KNB1ZTERM"] = strs[66]; dr["KNVVVKORG"] = strs[67]; dr["KNVVVTWEG"] = strs[68]; dr["KNVVSPART"] = strs[69]; dr["KNVVERNAM"] = strs[70]; if (strs[71] != "") { if (strs[71].Length == 8 && strs[71] != "00000000") { dr["KNVVERDAT"] = SplitDate(strs[71]);//date } else { dr["KNVVERDAT"] = DBNull.Value; } } else { dr["KNVVERDAT"] = DBNull.Value; } dr["KNVVLOEVM"] = strs[72]; dr["KNVVKALKS"] = strs[73]; dr["KNVVKONDA"] = strs[74]; dr["KNVVINCO1"] = strs[75]; dr["KNVVINCO2"] = strs[76]; dr["KNVVVSBED"] = strs[77]; dr["KNVVWAERS"] = strs[78]; dr["KNVVZTERM"] = strs[79]; dr["KNVVVWERK"] = strs[80]; dr["KNBKBANKS"] = strs[81]; dr["KNBKBANKL"] = strs[82]; dr["KNBKBANKN"] = strs[83]; dr["KNBKBKONT"] = strs[84]; dr["KNBKBKREF"] = strs[85]; dr["KNBKKOINH"] = strs[86]; dr["KNVKNAMEV"] = strs[87]; dr["KNVKNAME1"] = strs[88]; dr["KNVKTELF1"] = strs[89]; dr["BNKABANKA"] = strs[90];//97 个字段 mainsupplier.Rows.Add(dr); successMsg.AppendLine(string.Format("第{0}行公司:{1}客户行编码:{2}客户行名称:{3}成功", i + 1, dic[strs[59]], strs[0], strs[2])); successCount++; } } try { ExecuteMainData(mainsupplier, "MAIN_CUSTOMER"); } catch (Exception ex) { //LogInfo.Log.Error(ex); //exception = ex; throw ex; } Log(); }
public Common() { dt = new DataTable(); m_strMenu = new StringBuilder(); }
private void Form_CorteCaja_Load(object sender, EventArgs e) { try { DataTable dtInfoPedidos = ClsProcesoCorte.getInfoPedidos(); if (dtInfoPedidos.Rows.Count == 0) { MessageBox.Show("No existen ventas registradas"); textBox_Efectivo.Enabled = false; textBox_CreditoTC.Enabled = false; textBox_DebitoT.Enabled = false; textBox_Vales.Enabled = false; textBox_Cheque.Enabled = false; textBox_Otro.Enabled = false; button_CerrarCorte.Enabled = false; } DataTable ExistenPendientesCobro = ClsPedidos.getListaWhere(" WHERE iidEstatus = 1 AND iidCorte= 0 AND siPagado = 0 "); if (ExistenPendientesCobro.Rows.Count > 0) { DialogResult resp = MessageBox.Show(@"Existen ventas que estan pendientes de cobrar, aun asi desea realizarlo?", "Alerta", MessageBoxButtons.YesNo); if (DialogResult.No == resp) { textBox_Efectivo.Enabled = false; textBox_CreditoTC.Enabled = false; textBox_DebitoT.Enabled = false; textBox_Vales.Enabled = false; textBox_Cheque.Enabled = false; textBox_Otro.Enabled = false; button_CerrarCorte.Enabled = false; } } DataTable dtInfoTotales = ClsProcesoCorte.dtInfoPedidoTotales(); foreach (DataRow Row in dtInfoTotales.Rows) { ClsCorte.fVentaTotal = Convert.ToDouble(Row["VentaTotal"].ToString()); ClsCorte.fTotalDescuentos = Convert.ToDouble(Row["fDescuento"].ToString()); ClsCorte.fPropinaTotal = Convert.ToDouble(Row["fPropina"].ToString()); ClsCorte.fPromedioPersonas = Convert.ToDouble(Row["PromedioPersonas"].ToString()); ClsCorte.iPersonas = Convert.ToInt32(Row["PromedioPersonas"].ToString()); ClsCorte.fPromedioConsumo = Convert.ToDouble(Row["PromedioConsumo"].ToString()); ClsCorte.fMinPromedioEstancia = Convert.ToInt32(Row["minutos"].ToString()); ClsCorte.iNumPedidos = Convert.ToInt32(Row["NumPedidos"].ToString()); } DataTable dtInfoEntregas = ClsProcesoCorte.getTotalesFormas(); if (dtInfoEntregas.Rows.Count > 0) foreach (DataRow Row in dtInfoEntregas.Rows) { try { //Efectivo - 1 if (Row["iidFormaPago"].ToString() == "1") ClsCorte.fVentaEfectivo = Convert.ToDouble(Row["total"].ToString()); //TC credito - 4 if (Row["iidFormaPago"].ToString() == "4") ClsCorte.fVentaCreditoTC= Convert.ToDouble(Row["total"].ToString()); //T Debito - 18 if (Row["iidFormaPago"].ToString() == "18") ClsCorte.fVentaDebito = Convert.ToDouble(Row["total"].ToString()); //Vales - 7 if (Row["iidFormaPago"].ToString() == "7") ClsCorte.fVentaVales = Convert.ToDouble(Row["total"].ToString()); //cheque - 2 if (Row["iidFormaPago"].ToString() == "2") ClsCorte.fVentaCheque = Convert.ToDouble(Row["total"].ToString()); //otro - 20 if (Row["iidFormaPago"].ToString() == "20") ClsCorte.fVentaOtro = Convert.ToDouble(Row["total"].ToString()); } catch { MessageBox.Show("Problema de conversion, contacte al administrador"); } } //Saldo iniciales de caja DataTable saldosIniciales = ClsProcesoCorte.getMontosIniciales(); dgv_saldosIniciales.Columns.Add("Fecha", "Fecha"); dgv_saldosIniciales.Columns.Add("Personal", "Personal"); dgv_saldosIniciales.Columns.Add("Monto","Monto"); dgv_saldosIniciales.Columns["Fecha"].Width = 110; float saldoInicialtotal = 0; foreach (DataRow row in saldosIniciales.Rows) { dgv_saldosIniciales.Rows.Add(row["dFechaApertura"], row["nombre"], string.Format("{0:c}", row["fMontoInicial"])); saldoInicialtotal += float.Parse(row["fMontoInicial"].ToString()); } ClsCorte.fMontoInicial=saldoInicialtotal; ///Salidas y Entradas ClsCorte.fMontoEntradaDinero = 0; ClsCorte.fMontoSalidaDinero = 0; DataTable dtMovimientos = ClsProcesoCorte.dtMovimientos(); if (dtMovimientos.Rows.Count > 0) { ClsCorte.fMontoEntradaDinero = Convert.ToDouble(dtMovimientos.Rows[0]["Entrada"].ToString()); ClsCorte.fMontoSalidaDinero = Convert.ToDouble(dtMovimientos.Rows[0]["Salida"].ToString()); } ClsCorte.fTotalFinal = ClsCorte.fVentaTotal + ClsCorte.fMontoEntradaDinero - ClsCorte.fMontoSalidaDinero; label_MontoCaja.Text = string.Format("{0:c}", ClsCorte.fTotalFinal+ ClsCorte.fMontoInicial ); label_VentasTotales.Text = string.Format("{0:c}", ClsCorte.fVentaTotal); label_Entradas.Text = string.Format("{0:c}", ClsCorte.fMontoEntradaDinero); label_Salidas.Text ="- "+ string.Format("{0:c}", ClsCorte.fMontoSalidaDinero); //informacion de corte solo muestra ultima venta txt_cheque.Text = string.Format("{0:c}", ClsCorte.fVentaCheque); txt_efectivo.Text = string.Format("{0:c}", ClsCorte.fVentaEfectivo); txt_otro.Text = string.Format("{0:c}", ClsCorte.fVentaOtro); txt_tc.Text = string.Format("{0:c}", ClsCorte.fVentaCreditoTC); txt_td.Text = string.Format("{0:c}", ClsCorte.fVentaDebito); txt_vales.Text = string.Format("{0:c}", ClsCorte.fVentaVales); label_total_caja.Text = string.Format("{0:c}", ClsCorte.fTotalFinal+ ClsCorte.fMontoInicial ); label_inicial.Text = string.Format("{0:c}", ClsCorte.fMontoInicial); } catch { MessageBox.Show("Problema al crear el corte, notificar al administrador"); } }
protected void Page_Load(object sender, EventArgs e) { GridViewResultado.PreRender += GridViewResultado_PreRender; mAuthenticated = System.Web.HttpContext.Current.User.Identity.IsAuthenticated; if (!IsPostBack) { //Chave para exportação do CSV ChavePesquisa.Value = Guid.NewGuid().ToString(); HiddenFieldGrupo.Value = HttpUtility.HtmlDecode(Request.QueryString["grupo"]); HiddenFieldAgrupamento.Value = HttpUtility.HtmlDecode(Request.QueryString["agrupamentoNovo"]); HiddenFieldSeparaMes.Value = HttpUtility.HtmlDecode(Request.QueryString["separaMes"]); HiddenFieldPeriodo.Value = HttpUtility.HtmlDecode(Request.QueryString["periodo"]); HiddenFieldAnoIni.Value = HttpUtility.HtmlDecode(Request.QueryString["anoIni"]); HiddenFieldMesIni.Value = HttpUtility.HtmlDecode(Request.QueryString["mesIni"]); HiddenFieldAnoFim.Value = HttpUtility.HtmlDecode(Request.QueryString["anoFim"]); HiddenFieldMesFim.Value = HttpUtility.HtmlDecode(Request.QueryString["mesFim"]); HiddenFieldParlamentar.Value = HttpUtility.HtmlDecode(Request.QueryString["parlamentar"]); HiddenFieldDespesa.Value = HttpUtility.HtmlDecode(Request.QueryString["despesa"]); HiddenFieldFornecedor.Value = HttpUtility.HtmlDecode(Request.QueryString["fornecedor"]); HiddenFieldUF.Value = HttpUtility.HtmlDecode(Request.QueryString["uf"]); HiddenFieldPartido.Value = HttpUtility.HtmlDecode(Request.QueryString["partido"]); HiddenFieldDocumento.Value = HttpUtility.HtmlDecode(Request.QueryString["documento"]); String valorFiltro = HttpUtility.HtmlDecode(Request.QueryString["filtro"]); LabelFiltro.InnerText = HttpUtility.HtmlDecode(Request.QueryString["descricao"]); String agrupamentoAtual = HttpUtility.HtmlDecode(Request.QueryString["agrupamentoAtual"]); switch (agrupamentoAtual) { case Pesquisa.AGRUPAMENTO_PARLAMENTAR: HiddenFieldParlamentar.Value = valorFiltro; break; case Pesquisa.AGRUPAMENTO_DESPESA: HiddenFieldDespesa.Value = valorFiltro; break; case Pesquisa.AGRUPAMENTO_FORNECEDOR: HiddenFieldFornecedor.Value = valorFiltro; break; case Pesquisa.AGRUPAMENTO_PARTIDO: HiddenFieldPartido.Value = valorFiltro; break; case Pesquisa.AGRUPAMENTO_UF: HiddenFieldUF.Value = valorFiltro; break; case Pesquisa.AGRUPAMENTO_DOCUMENTO: HiddenFieldDocumento.Value = valorFiltro; HiddenFieldSeparaMes.Value = "false"; break; } Pesquisar(); } else { if (Request["__EVENTTARGET"] == "ButtonExportar_Click") { DataTable dtUltimaConsulta = HttpContext.Current.Session["AuditoriaUltimaConsulta" + ChavePesquisa.Value] as DataTable; if (dtUltimaConsulta != null) { DataTable dtExport = dtUltimaConsulta.Copy(); dtExport.Columns.RemoveAt(0); CsvHelper.ExportarCSV(dtExport); } } } }
public static object getObjectFromDatabase <T>(object searching = null, bool getDataTable = false) { object return_value = null; try { sqlConnection.Open(); string selectQuery = ""; int searchingProperties = 0; List <T> the_array = new List <T>(); if (searching != null) { foreach (PropertyInfo prop in searching.GetType().GetProperties()) { if (!((List <string>)searching.GetType().GetProperty("properties").GetValue(searching, null)).Contains(prop.Name.ToString())) { if (prop.GetValue(searching, null) != null || (prop.GetType() == typeof(string) && (string)prop.GetValue(searching, null) != "")) { if (!selectQuery.Contains(" WHERE ")) { selectQuery = " WHERE "; } selectQuery += "`" + prop.Name.ToString() + "` = '" + prop.GetValue(searching, null) + "' AND "; searchingProperties += 1; } } } selectQuery = selectQuery.Substring(0, selectQuery.LastIndexOf("AND") - 1); } //MessageBox.Show("SELECT * FROM `" + Activator.CreateInstance(typeof(T)).GetType().GetProperty("database_name").GetValue(Activator.CreateInstance(typeof(T)), null).ToString() + "`" + selectQuery); if (searching == null || (searching != null && searchingProperties > 0)) { using (SQLiteDataAdapter sqlAdapter = new SQLiteDataAdapter(new SQLiteCommand("SELECT * FROM `" + Activator.CreateInstance(typeof(T)).GetType().GetProperty("database_name").GetValue(Activator.CreateInstance(typeof(T)), null).ToString() + "`" + selectQuery, sqlConnection))) sqlAdapter.Fill(sqlDataTable = new DataTable()); if (getDataTable) { return_value = sqlDataTable; } else { using (sqlDataTable) { foreach (DataRow row in sqlDataTable.Rows) { try { dynamic this_object = Activator.CreateInstance(typeof(T)); anime_movie this_movie = new anime_movie(); foreach (DataColumn column in row.Table.Columns) { try { if (column.DataType == typeof(string)) { this_object.GetType().GetProperty(column.ColumnName).SetValue(this_object, (row[column] == DBNull.Value) ? string.Empty : row[column].ToString()); } else { this_object.GetType().GetProperty(column.ColumnName).SetValue(this_object, row[column]); } } catch (Exception) { /*Program.Main_Form.Log(ex.Message + " at: " + new StackTrace(ex, true).GetFrame(new StackTrace(ex, true).FrameCount - 1).GetFileLineNumber() + " with: " + column.ColumnName, "Error");*/ } } the_array.Add(this_object); } catch (Exception ex) { Program.Main_Form.log(ex.Message + " at: " + new StackTrace(ex, true).GetFrame(new StackTrace(ex, true).FrameCount - 1).GetFileLineNumber(), msgType.error); } } } return_value = the_array; } } else { return_value = new List <T>() { (T)Activator.CreateInstance(typeof(T)) } }; } catch (Exception ex) { Program.Main_Form.log(ex.Message + " at: " + new StackTrace(ex, true).GetFrame(new StackTrace(ex, true).FrameCount - 1).GetFileLineNumber(), msgType.error); } finally { if (sqlConnection.State == ConnectionState.Open) { sqlConnection.Close(); } } return(return_value); }
private void GetConsultationEntity() { if (m_ConsultationID == "") return; else { DataTable dt = DataAccess.GetConsultationTable(m_ConsultationID); DataTable dtinp = Dal.DataAccess.GetRedactPatientInfoFrm("14", CurrentInpatient.NoOfFirstPage.ToString()); foreach (DataRow dr in dt.Rows) { m_ConsultationEntity = new ConsultationEntity(); m_ConsultationEntity.ConsultApplySn = m_ConsultationID; m_ConsultationEntity.NoOfInpat = CurrentInpatient.NoOfFirstPage.ToString(); if (dtinp.Rows.Count > 0) { m_ConsultationEntity.Name = dtinp.Rows[0]["NAME"].ToString().Trim(); m_ConsultationEntity.PatNoOfHIS = dtinp.Rows[0]["PatID"].ToString().Trim(); m_ConsultationEntity.SexName = dtinp.Rows[0]["Gender"].ToString().Trim(); m_ConsultationEntity.Age = dtinp.Rows[0]["AgeStr"].ToString().Trim(); m_ConsultationEntity.Bed = dtinp.Rows[0]["OutBed"].ToString().Trim(); m_ConsultationEntity.DeptName = dtinp.Rows[0]["OutHosDeptName"].ToString().Trim(); m_ConsultationEntity.WardName = dtinp.Rows[0]["outhoswardname"].ToString().Trim(); m_ConsultationEntity.DeptID = dtinp.Rows[0]["OutHosDept"].ToString().Trim(); m_ConsultationEntity.WardID = dtinp.Rows[0]["outhosward"].ToString().Trim(); //textEditMarriage.Text = dtinp.Rows[0]["Marriage"].ToString().Trim(); //textEditJob.Text = dtinp.Rows[0]["JobName"].ToString().Trim(); } m_ConsultTypeID = dr["consulttypeid"].ToString(); m_ConsultationEntity.UrgencyTypeID = dr["urgencytypeid"].ToString(); m_ConsultationEntity.UrgencyTypeName = dr["urgencytypeName"].ToString(); m_ConsultationEntity.ConsultTypeID = dr["consulttypeid"].ToString(); m_ConsultationEntity.ConsultTypeName = dr["consulttypeName"].ToString(); m_ConsultationEntity.Abstract = dr["abstract"].ToString(); m_ConsultationEntity.Purpose = dr["purpose"].ToString(); m_ConsultationEntity.ApplyDeptID = dr["ApplyDeptID"].ToString(); m_ConsultationEntity.ApplyDeptName = dr["ApplyDeptName"].ToString(); m_ConsultationEntity.ApplyUserID = dr["applyuserID"].ToString(); m_ConsultationEntity.ApplyUserName = dr["applyuserName"].ToString(); m_ConsultationEntity.ApplyTime = dr["applytime"].ToString(); m_ConsultationEntity.ConsultSuggestion = dr["consultsuggestion"].ToString(); m_ConsultationEntity.ConsultDeptID = dr["ConsultDeptID"].ToString(); m_ConsultationEntity.ConsultDeptName = dr["ConsultDeptName"].ToString(); m_ConsultationEntity.ConsultHospitalID = dr["hospitalcode"].ToString(); m_ConsultationEntity.ConsultHospitalName = dr["ConsultHospitalName"].ToString(); m_ConsultationEntity.ConsultDeptID2 = dr["ConsultDeptID2"].ToString(); m_ConsultationEntity.ConsultDeptName2 = dr["ConsultDeptName2"].ToString(); m_ConsultationEntity.ConsultUserID = dr["ConsultUserID"].ToString(); m_ConsultationEntity.ConsultUserName = dr["ConsultUserName"].ToString(); m_ConsultationEntity.ConsultTime = dr["ConsultTime"].ToString(); m_ConsultationEntity.StateID = dr["StateID"].ToString(); return; } } }
private void button1_Click(object sender, EventArgs e) { string time = DateTime.Now.ToString("yyyy-MM-dd"); string s = this.comboBox1.GetItemText(this.comboBox1.SelectedItem); MessageBox.Show(s); string sex="0" ; string height="0"; cnn.Open(); string weight =" 0"; string cmdText = @"SELECT sex FROM myfitsecret.sportsman WHERE userid=@userid; SELECT daily_burned FROM myfitsecret.calorie_tracker WHERE sportsman_id=@sportsman_id"; using (MySqlCommand cmd = new MySqlCommand(cmdText, cnn)) { // Add both parameters to the same command cmd.Parameters.Add("@userid", MySqlDbType.String).Value = Login.userID; cmd.Parameters.Add("@sportsman_id", MySqlDbType.String).Value = Login.userID; using (MySqlDataReader reader = cmd.ExecuteReader()) { // get sum from the first result if (reader.Read()) sex = ((reader[0]).ToString()); // if there is a second resultset, go there if (reader.NextResult()) if (reader.Read() && !(reader[0] is DBNull)) Sportsman.burned += Convert.ToInt32(reader[0]); } cmd.Connection.Close(); cmdText = @"SELECT sportsman.height FROM myfitsecret.sportsman WHERE userid=@userid; SELECT body_progress.last_weight FROM myfitsecret.body_progress WHERE sportsmanID=@sportsmanID"; using (MySqlCommand cmd2 = new MySqlCommand(cmdText, cnn)) { cmd2.Connection.Open(); // Add both parameters to the same command cmd2.Parameters.Add("@userid", MySqlDbType.String).Value = Login.userID; cmd2.Parameters.Add("@sportsmanID", MySqlDbType.String).Value = Login.userID; using (MySqlDataReader reader2 = cmd2.ExecuteReader()) { // get sum from the first result if (reader2.Read()) height = (reader2[0]).ToString(); // if there is a second resultset, go there if (reader2.NextResult()) if (reader2.Read()) weight = (reader2[0]).ToString(); } cmd2.Connection.Close(); if (Sportsman.count1 == 0) { if (sex.Equals("male") && s.Equals("weightTraining")) { Sportsman.burned1 += 700 + (15 * int.Parse(weight)) + (5 * int.Parse(height)) - (7 * 30) + (int.Parse(textBox1.Text) * 14); MessageBox.Show("Burned calories are updated"); } else if (sex.Equals("male") && s.Equals("cardio")) { Sportsman.burned1 += 700 + (15 * int.Parse(weight)) + (5 * int.Parse(height)) - (7 * 30) + (int.Parse(textBox1.Text) * 10); MessageBox.Show("Burned calories are updated"); } else if (sex.Equals("female") && s.Equals("weightTraining")) { Sportsman.burned1 += 900 + (9 * int.Parse(weight)) + (2 * int.Parse(height)) - (5 * 30) + (int.Parse(textBox1.Text) * 10); MessageBox.Show("Burned calories are updated"); } else { Sportsman.burned1 += 900 + (9 * int.Parse(weight)) + (2 * int.Parse(height)) - (5 * 30) + (int.Parse(textBox1.Text) * 6); MessageBox.Show("Burned calories are updated"); } MySqlCommand cmd5 = new MySqlCommand("UPDATE myfitsecret.calorie_tracker set daily_burned=@daily_burned where sportsman_id=@sportsman_id and Date=@Date", cnn); cmd5.CommandType = CommandType.Text; cmd5.Connection.Open(); cmd5.Parameters.AddWithValue("@daily_burned", Sportsman.burned1); cmd5.Parameters.AddWithValue("@Date", time); cmd5.Parameters.Add("@sportsman_id", MySqlDbType.String).Value = Login.userID; cmd5.ExecuteNonQuery(); cmd5.Connection.Close(); Sportsman.count1++; } else { if (sex.Equals("male")) Sportsman.burned1 += (int.Parse(textBox1.Text) * 10); else Sportsman.burned1 += (int.Parse(textBox1.Text) * 6); MySqlCommand cmd3 = new MySqlCommand("update myfitsecret.calorie_tracker set daily_burned=@daily_burned where sportsman_id=@sportsman_id and Date=@Date", cnn); cmd3.CommandType = CommandType.Text; cmd3.Connection.Open(); cmd3.Parameters.AddWithValue("@daily_burned", Sportsman.burned1); cmd3.Parameters.AddWithValue("@Date", time); cmd3.Parameters.Add("@sportsman_id", MySqlDbType.String).Value = Login.userID; cmd3.ExecuteNonQuery(); } DataTable tablo = new DataTable(); string showTable = "SELECT daily_gained,daily_burned,Date from myfitsecret.calorie_tracker where sportsman_id=@sportsman_id"; MySqlDataAdapter adapter = new MySqlDataAdapter(); MySqlCommand showCommand = new MySqlCommand(); showCommand.Connection = cnn; showCommand.CommandText = showTable; showCommand.CommandType = CommandType.Text; showCommand.Parameters.AddWithValue("@sportsman_id", Login.userID); adapter.SelectCommand = showCommand; adapter.Fill(tablo); dataGridView1.DataSource = tablo; cmd.Connection.Close(); cnn.Close(); } } }
/// <summary> /// Implementation of reading a csv which is specific to the way this sample /// is implemented. Your mileage may vary. Change to suit your purposes as /// needed. /// </summary> private void Open() { var lstDoubleFields = new List<int>(); var lstLongFields = new List<int>(); var lstDateFields = new List<int>(); //Read in the CSV TextFieldParser parser = new TextFieldParser(_path); parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited; parser.SetDelimiters(","); parser.HasFieldsEnclosedInQuotes = true; //Initialize our data table _table = new DataTable(); //dataTable.PrimaryKey = new DataColumn("OBJECTID", typeof(long)); var oid = new DataColumn("OBJECTID", typeof(Int32)) { AutoIncrement = true, AutoIncrementSeed = 1 }; _table.Columns.Add(oid); _table.PrimaryKey = new DataColumn[] { oid }; //First line must be the column headings var fieldIdx = 0; foreach (var field in parser.ReadFields()) { var field_name = field.Replace(' ', '_').ToUpper(); if (field_name.Length == 1 || field_name.StartsWith("POINT_")) { // field name is X or Y _table.Columns.Add(new DataColumn(field_name, typeof(double))); lstDoubleFields.Add(fieldIdx); } else if (field_name.StartsWith ("LONG_")) { _table.Columns.Add(new DataColumn(field_name, typeof(long))); lstLongFields.Add(fieldIdx); } else if (field_name.StartsWith ("DATE_")) { _table.Columns.Add(new DataColumn(field_name, typeof(DateTime))); lstDateFields.Add(fieldIdx); } else _table.Columns.Add(new DataColumn(field_name, typeof(string))); fieldIdx++; } //For spatial data... //Domain to verify coordinates (2D) var sr_extent = new RBush.Envelope( minX: _sr.Domain.XMin, minY: _sr.Domain.YMin, maxX: _sr.Domain.XMax, maxY: _sr.Domain.YMax ); //default to the Spatial Reference domain _extent = sr_extent; bool hasSpatialData = false; bool haveDeterminedSpatialData = false; //The first two fields are assumed to be the X and Y coordinates of a point //otherwise the file is treated as a table and not a feature class //The third field (if there is one) is checked for Z. while (!parser.EndOfData) { var values = parser.ReadFields(); if (!haveDeterminedSpatialData) { if (values.Count() >= 2) { double test = 0; if (Double.TryParse(values[0], out test)) { hasSpatialData = Double.TryParse(values[1], out test); if (hasSpatialData) { //add a shape column _table.Columns.Add(new DataColumn("SHAPE", typeof(System.Byte[]))); //do we have a Z? double z = 0; _hasZ = false; if (values.Count() >= 3) { _hasZ = Double.TryParse(values[2], out z); } } } } haveDeterminedSpatialData = true; } //load the datatable var row = _table.NewRow(); for (int c = 0; c < values.Length; c++) { //TODO Deal with nulls!! // check double types if (lstDoubleFields.Contains(c)) { row[c + 1] = System.DBNull.Value; // field value is double if (Double.TryParse(values[c], out double dValue)) { row[c + 1] = dValue;//Column "0" is our objectid } } else if (lstLongFields.Contains(c)) { row[c + 1] = System.DBNull.Value; // field value is long if (int.TryParse(values[c], out int iValue)) { row[c + 1] = iValue;//Column "0" is our objectid } } else if (lstDateFields.Contains(c)) { row[c + 1] = System.DBNull.Value; // field value is datetime if (DateTime.TryParse(values[c], out DateTime dateValue)) { row[c + 1] = dateValue;//Column "0" is our objectid } } else { row[c + 1] = values[c] ?? "";//Column "0" is our objectid } } if (hasSpatialData) { double x = 0, y = 0, z = 0; //TODO Deal with nulls! Double.TryParse(values[0], out x); Double.TryParse(values[1], out y); //do we have a Z? if (_hasZ) { //TODO Deal with nulls! Double.TryParse(values[2], out z); } //ensure the coordinate is within bounds var coord = new Coordinate3D(x, y, z); if (!sr_extent.Contains2D(coord)) throw new ArcGIS.Core.Data.GeodatabaseFeatureException( "The feature falls outside the defined spatial reference"); //store it row["SHAPE"] = coord.ToMapPoint().ToEsriShape(); //add it to the index var rbushCoord = new RBushCoord3D(coord, (int)row["OBJECTID"]); _rtree.Insert(rbushCoord); //update max and min for use in the extent if (_rtree.Count == 1) { //first record _extent = rbushCoord.Envelope; } else { _extent = rbushCoord.Envelope.Union2D(_extent); } } _table.Rows.Add(row); } }
///******************************************************************************* ///NOMBRE DE LA FUNCIÓN: Txt_Contenedor_KeyPress ///DESCRIPCIÓN : Evento KeyPress del Txt_Contenedor para consultar el contenedor ingresado /// al presionar la tecla Enter ///PARAMENTROS : ///CREO : Miguel Angel Bedolla Moreno ///FECHA_CREO : 12/Abr/2013 05:27 p.m. ///MODIFICO : ///FECHA_MODIFICO: ///CAUSA_MODIFICACIÓN: ///******************************************************************************* private void Txt_Contenedor_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Enter) { if (Txt_Contenedor.Text.Trim() != "") { Cls_Cat_Contenedores_Negocio P_Contenedores = new Cls_Cat_Contenedores_Negocio(); DataTable Dt_Contenedor_Cargar = new DataTable(); P_Contenedores.P_Codigo_Contenedor = Txt_Contenedor.Text.ToUpper().Replace("-", ""); P_Contenedores.P_Estatus = " = 'ACTIVO'"; P_Contenedores.P_Uso = " LIKE '%FG%'"; P_Contenedores.P_Contenedor_No_Embarque = true; Dt_Contenedor_Cargar = P_Contenedores.Consultar_Contenedores(); if (Dt_Contenedor_Cargar.Rows.Count > 0) { Txt_Contenedor_Id.Text = Dt_Contenedor_Cargar.Rows[0][Cat_Contenedores.Campo_Contenedor_Id].ToString(); Txt_Tipo_Contenedor_Id.Text = Dt_Contenedor_Cargar.Rows[0][Cat_Contenedores.Campo_Tipo_Contenedor_Id].ToString(); Txt_Tipo_Contenedor.Text = Dt_Contenedor_Cargar.Rows[0]["TIPO_CONTENEDOR"].ToString(); } else { Txt_Contenedor_Id.Text = ""; Txt_Contenedor.Text = ""; Txt_Tipo_Contenedor.Text = ""; Txt_Tipo_Contenedor_Id.Text = ""; MessageBox.Show("*El contenedor no existe en el sistema ó \n*El contenedor esta INACTIVO ó, \n*El contenedor se encuentra en un embarque.", "Salida de contenedores", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } if (Txt_Contenedor_Id.Text.Trim() != "") { DataTable Dt_Contenedores = (DataTable)Grid_Contenedores_Embarque.DataSource; foreach (DataRow Dr_Contenedor in Dt_Contenedores.Rows) { if (Dr_Contenedor["CONTENEDOR_ID"].ToString() == Txt_Contenedor_Id.Text) { Txt_Contenedor_Id.Text = ""; Txt_Contenedor.Text = ""; Txt_Tipo_Contenedor.Text = ""; Txt_Tipo_Contenedor_Id.Text = ""; MessageBox.Show("*El contenedor ya se encuentra cargado.", "Salida de contenedores", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } } } if (Txt_Contenedor_Id.Text.Trim() != "") { Boolean Entro = false; for (int Cont_Contenedores = 0; Cont_Contenedores < Dt_Configuracion.Rows.Count; Cont_Contenedores++) { if (Dt_Configuracion.Rows[Cont_Contenedores][Cat_Tipos_Contenedores.Campo_Tipo_Contenedor_Id].ToString() == Txt_Tipo_Contenedor_Id.Text) { Entro = true; } } if (!Entro) { Txt_Contenedor_Id.Text = ""; Txt_Contenedor.Text = ""; Txt_Tipo_Contenedor.Text = ""; Txt_Tipo_Contenedor_Id.Text = ""; MessageBox.Show("*El tipo de contenedor no se encuentra especificado en la órden de salida", "Salida de contenedores", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } } if (Txt_Contenedor_Id.Text.Trim() != "") { Boolean Entro = false; for (int Cont_Contenedores = 0; Cont_Contenedores < Dt_Configuracion.Rows.Count; Cont_Contenedores++) { if (Dt_Configuracion.Rows[Cont_Contenedores][Cat_Tipos_Contenedores.Campo_Tipo_Contenedor_Id].ToString() == Txt_Tipo_Contenedor_Id.Text && (Convert.ToDouble(Dt_Configuracion.Rows[Cont_Contenedores]["CONTENEDORES"].ToString()) < Convert.ToDouble(Dt_Configuracion.Rows[Cont_Contenedores][Ope_Detalles_Orden_Salida.Campo_Cantidad_Contenedores].ToString()))) { Entro = true; } } if (!Entro) { Txt_Contenedor_Id.Text = ""; Txt_Contenedor.Text = ""; MessageBox.Show("*El tipo de contenedor: " + Txt_Tipo_Contenedor.Text + " se encuentra completo en la orden de salida.", "Salida de contenedores", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); Txt_Tipo_Contenedor.Text = ""; Txt_Tipo_Contenedor_Id.Text = ""; } } if (Txt_Contenedor_Id.Text.Trim() != "") { DataRow Dr_Renglon_Nuevo; DataTable Dt_Contenedor = (DataTable)Grid_Contenedores_Embarque.DataSource; Dr_Renglon_Nuevo = Dt_Contenedor.NewRow(); Dr_Renglon_Nuevo["CONTENEDOR_ID"] = Txt_Contenedor_Id.Text; Dr_Renglon_Nuevo["COMENTARIOS"] = ""; Dr_Renglon_Nuevo["CONTENEDOR"] = Dt_Contenedor_Cargar.Rows[0]["CODIGO_CONTENEDOR"].ToString(); Dt_Contenedor.Rows.Add(Dr_Renglon_Nuevo); Dt_Contenedor.TableName = "CONT_EMBARQUE"; Grid_Contenedores_Embarque.DataSource = Dt_Contenedor; for (int Cont_Contenedores = 0; Cont_Contenedores < Dt_Configuracion.Rows.Count; Cont_Contenedores++) { if (Dt_Configuracion.Rows[Cont_Contenedores][Cat_Tipos_Contenedores.Campo_Tipo_Contenedor_Id].ToString() == Txt_Tipo_Contenedor_Id.Text) { Dt_Configuracion.Rows[Cont_Contenedores]["CONTENEDORES"] = Convert.ToDouble(Dt_Configuracion.Rows[Cont_Contenedores]["CONTENEDORES"].ToString()) + 1; } } Txt_Comentarios.Text = ""; Txt_Contenedor.Text = ""; Txt_Contenedor_Id.Text = ""; Txt_Contenedor.Focus(); Boolean Entro = false; for (int Cont_Contenedores = 0; Cont_Contenedores < Dt_Configuracion.Rows.Count; Cont_Contenedores++) { if ((Convert.ToDouble(Dt_Configuracion.Rows[Cont_Contenedores]["CONTENEDORES"].ToString()) < Convert.ToDouble(Dt_Configuracion.Rows[Cont_Contenedores][Ope_Detalles_Orden_Salida.Campo_Cantidad_Contenedores].ToString()))) { Entro = true; } } if (!Entro) { Btn_Nuevo_Click(null, null); } } } } }
// This method reads the attributes of your container class via reflection in order to // build a schema for the DataTable that you will explicitly convert to. private DataTable ConstructDataTableSchema(T item) { string tblName = string.Empty; List <DataTableConverterContainer> schCon = new List <DataTableConverterContainer>(); Type newType = item.GetType(); MemberInfo[] newMemsInfo = newType.GetProperties(); foreach (MemberInfo newMemInfo in newMemsInfo) { object[] newAtts = newMemInfo.GetCustomAttributes(true); if (newAtts.Length != 0) { foreach (object newAtt in newAtts) { ConversionAttribute newConAtt = newAtt as ConversionAttribute; if (newConAtt != null) { if (newConAtt.ConvertDataTable) { // The name of the container class is used to name your DataTable string[] newClsNameArr = newMemInfo.ReflectedType.ToString().Split(Convert.ToChar(".")); tblName = newClsNameArr[newClsNameArr.Length - 1]; string newName = newMemInfo.Name.ToString(); PropertyInfo propInfo = newType.GetProperty(newName); Type NewValType = propInfo.GetValue(item, null).GetType(); // Each property that is will be a column in our DataTable. schCon.Add(new DataTableConverterContainer(newName, NewValType, newConAtt.DBNull, newConAtt.KeyFields)); } } } } } if (schCon.Count > 0) { DataTable newDataTbl = new DataTable(tblName); DataColumn[] newDataCol = new DataColumn[schCon.Count]; // Counts the number of keys that will need to be created int numberOfKeys = 0; foreach (DataTableConverterContainer newContainer in schCon) { if (newContainer.CheckKey == true && _enforceKeys == true) { numberOfKeys = numberOfKeys + 1; } } // Builds the DataColumns for our DataTable DataColumn[] newKeyColArr = new DataColumn[numberOfKeys]; int keyColIdx = 0; for (int i = 0; i < schCon.Count; i++) { newDataCol[i] = new DataColumn(); newDataCol[i].DataType = schCon[i].PropType; newDataCol[i].ColumnName = schCon[i].PropName; newDataCol[i].AllowDBNull = schCon[i].CheckDbNull; newDataTbl.Columns.Add(newDataCol[i]); if (schCon[i].CheckKey == true && _enforceKeys == true) { newKeyColArr[keyColIdx] = newDataCol[i]; keyColIdx = keyColIdx + 1; } } if (_enforceKeys) { newDataTbl.PrimaryKey = newKeyColArr; } return(newDataTbl); } return(null); }
protected void GridViewFriends_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName.CompareTo("FriendsReject") == 0) { SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["ShopConnectionString"].ConnectionString); SqlCommand sqlCmd; try { sqlCmd = new SqlCommand("sp_requestsConnectionsFriendsReject", sqlConn); sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Parameters.Add("@RequestId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument.ToString()); sqlConn.Open(); sqlCmd.ExecuteNonQuery(); } catch { } finally { sqlConn.Close(); } GridViewFriends.DataBind(); } if (e.CommandName.CompareTo("FriendsAccept") == 0) { SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["ShopConnectionString"].ConnectionString); SqlCommand sqlCmd; try { DataTable dt = new DataTable(); DataTable dt2 = new DataTable(); DataSet ds = new DataSet(); SqlDataAdapter sda = new SqlDataAdapter("sp_requestsConnectionsFriendsVerify", sqlConn); sda.SelectCommand.CommandType = CommandType.StoredProcedure; sda.SelectCommand.Parameters.Add("@RequestId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument.ToString()); sda.SelectCommand.Parameters.Add("@UserId", SqlDbType.Int).Value = Convert.ToInt32(Session["UserId"]); sda.Fill(ds); dt = ds.Tables[0]; dt2 = ds.Tables[1]; NotificationsClass nc = new NotificationsClass(); nc.addNotification(1, Convert.ToInt32(dt.Rows[0]["FriendId"].ToString()), 7, dt2.Rows[0]["FullName"].ToString(), ""); } catch { } finally { sqlConn.Close(); } GridViewFriends.DataBind(); } }