protected void Page_Load(object sender, EventArgs e) { #region Check Login CheckRegionAdminSession(); #endregion Check Login #region Initialize Values and Form Execution strPortfolioID = CCLib.Common.Strings.GetQueryString("PortfolioID"); dtPortInfo = CCLib.Common.DataAccess.GetDataTable("select p.Username,GradeNumber,FirstName,LastName,p.UserName,u.institutionName from Portfolio p join Userinfo u on p.Schoolid = u.schoolid where portfolioid=" + strPortfolioID); strSQL = " select p.Username,p.Fullname,p.Address,p.City,p.State,p.Zip,p.Phone,p.Email,p.Password,p.IsImport "; strSQL += " from Port_Parent_View as p join Portfolio on p.Username = Portfolio.Username "; strSQL += " where PortfolioID=" + strPortfolioID + " and p.PortTypeID=" + PortTypeID; dtParents = CCLib.Common.DataAccess.GetDataTable(strSQL); drsParentByImport = dtParents.Select("IsImport=1"); drsParentByInput = dtParents.Select("IsImport=0"); strUsername = (dtPortInfo.Rows.Count > 0) ? dtPortInfo.Rows[0]["Username"].ToString() : ""; #endregion Initialize Values and Form Execution #region Properties For The Region Base Class TitleBar = "Parent/Guardian Access Accounts"; SubTitleBar = "Parent/Guardian Access Accounts"; #endregion Properties For The Region Base Class }
private static void FillMenus(THOK.AF.Config config, DataTable moduleTable, DataTable functionTable) { DataRow[] moduleRows = moduleTable.Select("PARENTID='000000'", "SHOWORDER"); foreach (DataRow moduleRow in moduleRows) { DataRow[] menuRows = moduleTable.Select(string.Format("PARENTID='{0}'", moduleRow["MODULEID"]), "SHOWORDER"); List<THOK.AF.Menu> menus = new List<THOK.AF.Menu>(); foreach (DataRow menuRow in menuRows) { string menuID = menuRow["MODULEID"].ToString(); THOK.AF.Menu menu = new THOK.AF.Menu(menuRow["MODULENAME"].ToString(), menuRow["MODULEURL"].ToString(), menuID); menus.Add(menu); if (functionTable != null) { DataRow[] functionRows = functionTable.Select(string.Format("MODULEID='{0}'", menuID)); foreach (DataRow row in functionRows) config.AddFunction(menuID, row["CONTROLNAME"].ToString()); } } if (menus.Count != 0) { THOK.AF.MenuList menuList = new THOK.AF.MenuList(moduleRow["MODULENAME"].ToString(), menus); config.MenuList.Add(menuList); } } }
private static void DataTableToJson(StringBuilder result, StringBuilder temp, DataTable table, string idColumn, string textColumn, string relativeColumn, object parentId) { result.Append(temp.ToString()); temp.Clear(); if (table.Rows.Count > 0) { temp.Append("["); string filer = string.Format("{0}='{1}'", relativeColumn, parentId); DataRow[] rows = table.Select(filer); if (rows.Length > 0) { foreach (DataRow row in rows) { temp.Append("{\"id\":\"" + row[idColumn] + "\",\"text\":\"" + row[textColumn] + "\",\"state\":\"open\""); if (table.Select(string.Format("{0}='{1}'", relativeColumn, row[idColumn])).Length > 0) { temp.Append(",\"children\":"); DataTableToJson(result, temp, table, idColumn, textColumn, relativeColumn, row[idColumn]); result.Append(temp.ToString()); temp.Clear(); } result.Append(temp.ToString()); temp.Clear(); temp.Append("},"); } temp = temp.Remove(temp.Length - 1, 1); } temp.Append("]"); result.Append(temp.ToString()); temp.Clear(); } }
public void ExportToExcel(WGJG02ByUnitID model) { //1.0获取待导出数据 System.Data.DataTable dt = DBSession.IWGJG02DAL.GetExportData(model); Dictionary <string, string> dict = new Dictionary <string, string>(); dict.Add("A0101", "姓名"); dict.Add("B0002", "用工单位"); dict.Add("UnitID", "用工单位"); dict.Add("E0386", "工种"); dict.Add("WGJG0203", "发放方式"); dict.Add("WGJG0202", "约定发放时间"); dict.Add("WGJG0201", "确定时间"); dict.Add("WGJG0207", "应发金额"); dict.Add("WGJG0208", "实发金额"); if (dt != null) { DataRow row = dt.NewRow(); row["A0101"] = "合计"; row["WGJG0207"] = dt.Select(" WGJG0207 IS NOT NULL").AsEnumerable().Select(d => d.Field <decimal>("WGJG0207")).Sum(); row["WGJG0208"] = dt.Select(" WGJG0208 IS NOT NULL").AsEnumerable().Select(d => d.Field <decimal>("WGJG0208")).Sum(); dt.Rows.Add(row); } HCQ2_Common.NpoiHelper.DataTableToExeclForNpoi(dt, dict, "发放汇总", "发放汇总", "A0177", true, ",WGJG0207,WGJG0208,"); }
//给下拉框赋值,数据可在主数据维护表Basic_UploadPicture中修改 public void AssignmentForLookUpEdit() { string[] l_s = new string[] { "DisplayValue", "Value", "Categoryflag" }; string category = "Basic_UploadPicture"; System.Data.DataTable dt_PVLine = BaseData.Get(l_s, category); DataRow[] drDestRootPath = dt_PVLine.Select(string.Format("Categoryflag='{0}'", "DestRootPath")); DataRow[] drFileExistention = dt_PVLine.Select(string.Format("Categoryflag='{0}'", "FileExistention")); if (drDestRootPath.Length > 0 && drDestRootPath != null) { DataTable dt = drDestRootPath[0].Table.Clone(); foreach (DataRow dr in drDestRootPath) { dt.ImportRow(dr); } luDestRootPath.Properties.DataSource = dt; luDestRootPath.Properties.DisplayMember = "DisplayValue"; luDestRootPath.Properties.ValueMember = "Value"; luDestRootPath.Properties.NullText = ""; } if (drFileExistention.Length > 0 && drFileExistention != null) { DataTable dt = drFileExistention[0].Table.Clone(); foreach (DataRow dr in drFileExistention) { dt.ImportRow(dr); } luFileExistention.Properties.DataSource = dt; luFileExistention.Properties.DisplayMember = "DisplayValue"; luFileExistention.Properties.ValueMember = "Value"; luFileExistention.Properties.NullText = ""; } }
protected void Page_Load(object sender, EventArgs e) { LoginID = Request.QueryString["LoginID"]; LoginInfo = CCLib.Login.GetLoginInfo(LoginID); Redirect(); PageTitle = "Ability Profiler"; Section = "mm"; CSS = "global_css"; HeadTag = "<style type='TEXT/CSS'><!--.btnDescription { font: 11px Verdana, Arial, Helvetica, sans-serif; margin: 0px 15px}--></style>"; BodyTag = " alink='#990000' style='background-image:url(/media/shared/bg_else.gif); background-repeat:no-repeat; background-color:#FFFFFF;' leftmargin=0 link='#003366' text='#000000' topmargin=0 vlink='#003366' marginwidth='0' marginheight='0'"; LeftBar = "<table border='0' cellpadding='0' cellspacing='0' style='width:100%;'><tr style='background-color:#336699; vertical-align:top;'><td style='background-image:url(/media/mm/i_top_bar_bg.gif);'><img src='/media/mm/i_c_mm_icon.gif' alt=''><img src='/media/mm/h_c_mm.gif' alt='" + TextCode(273) + "'>"; HasTopCenterButtons = false; ClientScript.RegisterClientScriptBlock(Page.GetType(), "Reconnect", CCLib.Login.AddKeepAlive()); strSection = (CCLib.Common.Strings.GetQueryString("SID") == "") ? "0" : CCLib.Common.Strings.GetSecureQueryString("SID"); strTestID = (CCLib.Common.Strings.GetQueryString("TID") == "") ? "0" : CCLib.Common.Strings.GetSecureQueryString("TID"); strRegID = (CCLib.Common.Strings.GetQueryString("RID") == "") ? "0" : CCLib.Common.Strings.GetSecureQueryString("RID"); strResult = CCLib.Common.Strings.GetQueryString("Result"); intCurrPart = Convert.ToInt16(strSection) - 1; strSQL = "SELECT SectionID, SectionName_EN, SectionNameCapital_EN, SectionDescription_EN, ExampleDescription_EN, PracticeDescription_EN, Timer, "; strSQL += " NumberOfSlotsInOnePage, NumberOfQuestionInSlot, LayoutType,TotalQuestions FROM AP_Section"; dtbSection = CCLib.Cache.GetCachedDataTable("AP_Section" + CCLib.Common.Strings.SuffixCode(), strSQL); drsCurrSection = dtbSection.Select("SectionID=" + intCurrPart.ToString()); strSectionName = drsCurrSection[0]["SectionNameCapital" + SuffixCode()].ToString(); if (intCurrPart < 6) { drsNextSection = dtbSection.Select("SectionID=" + strSection); strNextSectionTimer = drsNextSection[0]["Timer"].ToString(); } strSection = Server.UrlEncode(CCLib.Common.Strings.SetSecureQueryString("SID", strSection)); strTestID = Server.UrlEncode(CCLib.Common.Strings.SetSecureQueryString("TID", strTestID)); strRegID = Server.UrlEncode(CCLib.Common.Strings.SetSecureQueryString("RID", strRegID)); }
/// 修改:李东峰 日期:2014-2-28 /// 修改内容:增加根据visible属性判断是否显示该菜单 public void GetLeftTree(string id) { string userId = Request.Cookies["T_USERID"].Value.ToString(); string roleId = bl.GetRoleId(userId); dt = new DataTable(); GetTreeList(); DataRow[] _dr = dt.Select("PID='" + id + "'"); IList<Hashtable> list = new List<Hashtable>(); for (int i = 0; i < _dr.Length; i++) { string[] nodeRoleId = _dr[i][5].ToString().TrimStart(',').TrimEnd(',').Split(','); if (nodeRoleId.Contains(roleId) && _dr[i][4].ToString() == "1") { Hashtable ht = new Hashtable(); ht.Add("ID", _dr[i][0].ToString()); ht.Add("NAME", _dr[i][1].ToString()); DataRow[] _dr_judge = dt.Select("PID='" + _dr[i][0].ToString() + "'"); if (_dr_judge.Length > 0) ht.Add("JUDGE", "1"); else ht.Add("JUDGE", "0"); list.Add(ht); } } object obj = new { list = list }; string result = Newtonsoft.Json.JsonConvert.SerializeObject(obj); Response.Write(result); Response.End(); }
protected void rptList_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e) { if (e.Item.ItemType == System.Web.UI.WebControls.ListItemType.Item || e.Item.ItemType == System.Web.UI.WebControls.ListItemType.AlternatingItem) { int groupId = (int)System.Web.UI.DataBinder.Eval(e.Item.DataItem, "Id"); int num = 0; int num2 = 0; int num3 = 0; System.Data.DataTable customGroupingUser = CustomGroupingHelper.GetCustomGroupingUser(groupId); if (customGroupingUser.Rows.Count > 0) { num = customGroupingUser.Select("LastOrderDate is null").Length; int activeDay = MemberHelper.GetActiveDay(); num2 = customGroupingUser.Select(" PayOrderDate is not null and PayOrderDate >='" + System.DateTime.Now.AddDays((double)(-(double)activeDay)).ToString("yyyy-MM-dd HH:mm:ss") + "'").Length; num3 = customGroupingUser.Select(" PayOrderDate is null or PayOrderDate <'" + System.DateTime.Now.AddDays((double)(-(double)activeDay)).ToString("yyyy-MM-dd HH:mm:ss") + "'").Length; } System.Web.UI.WebControls.Literal literal = e.Item.FindControl("ltMemberNumList") as System.Web.UI.WebControls.Literal; literal.Text = string.Concat(new object[] { "<td>", num, "</td><td>", num2, "</td><td>", num3, "</td>" }); } }
/// <summary> /// 获取实际的积分,没有启用为 0 ,没有配置 使用父级 ,启用使自己 ///.(1, "发主题"); ///.(2, "发回复"); ///.(3, "设置精华"); ///.(4, "取消精华"); ///.(5, "删除主题"); ///.(6, "删除回复"); ///.(7, "上传附件"); ///.(8, "下载附件"); /// </summary> /// <param name="board_id"></param> /// <param name="Action_id"></param> /// <returns></returns> public int GetRealPoint(int board_id, int action_id) { int _point = 0; System.Data.DataTable dt = GetList(" BoardId in (0," + board_id + ") and ActionId=" + action_id).Tables[0]; if (dt.Rows.Count != 0) { System.Data.DataRow[] dr1 = dt.Select("BoardId=" + board_id); //不存在则使用父级 if (dr1.Length == 0) { System.Data.DataRow[] dr2 = dt.Select("BoardId=0"); if (dr2.Length != 0) { _point = Convert.ToInt32(dr2[0]["Point"]); } } else { //启用返回实际 if (Convert.ToInt32(dr1[0]["Enable"]) == 1) { _point = Convert.ToInt32(dr1[0]["Point"]); } } } return(_point); }
private void m_lsvCheckItem_Click(object sender, System.EventArgs e) { if (this.m_lsvCheckItem.SelectedItems.Count <= 0) { return; } string strCheckItemEnglishName = ((clsCheckItem_VO)this.m_lsvCheckItem.SelectedItems[0].Tag).m_strCheck_Item_English_Name.ToString().Trim(); string strCheckItemID = ((clsCheckItem_VO)this.m_lsvCheckItem.SelectedItems[0].Tag).m_strCheck_Item_ID.ToString().Trim(); string strCheckItem = "[" + strCheckItemID + " " + strCheckItemEnglishName + "]"; int intIdx = this.m_rtbFormula.SelectionStart; int intLength = this.m_rtbFormula.SelectionLength; this.m_rtbFormula.Text = this.m_rtbFormula.Text.Remove(intIdx, intLength); this.m_rtbFormula.Text = this.m_rtbFormula.Text.Insert(intIdx, "[" + strCheckItemID + " " + strCheckItemEnglishName + "]"); this.m_rtbFormula.SelectionStart = intIdx + strCheckItem.Length; this.m_rtbFormula.SelectionLength = 0; //添加选中的项目到DataTable DataRow[] drArr = null; if (m_dtbAddCheckItem.Rows.Count > 0) { drArr = m_dtbAddCheckItem.Select("CHECK_ITEM_ID_CHR = " + strCheckItemID); } if (drArr == null || drArr.Length <= 0) { DataRow dr = m_dtbAddCheckItem.NewRow(); dr["CHECK_ITEM_ID_CHR"] = strCheckItemID; dr["CHECK_ITEM_ENGLISH_NAME_VCHR"] = strCheckItemEnglishName; m_dtbAddCheckItem.Rows.Add(dr); } this.m_rtbFormula.Focus(); }
protected void Page_Load(object sender, EventArgs e) { #region Check Login CheckStateAdminSession(); #endregion Check Login #region Initialize Values and Form Execution strPortfolioID = CCLib.Common.Strings.GetQueryString("PortfolioID"); // set header info control HeaderInfo.PortfolioID = strPortfolioID; HeaderInfo.StateSystem = AdminInfo["State"].ToString(); dtStudent = CCLib.Common.DataAccess.GetDataTable("select username,isnull(FirstName,'') + ' ' + LastName as FullName from portfolio where portfolioid=" + strPortfolioID); strSQL = " select p.Username,p.Fullname,p.Address,p.City,p.State,p.Zip,p.Phone,p.Email,p.Password,p.IsImport "; strSQL += " from Port_Parent_KY as p join Portfolio on p.Username = Portfolio.Username "; strSQL += " where PortfolioID=" + strPortfolioID + " and p.IsActive=1"; dtParents = CCLib.Common.DataAccess.GetDataTable(strSQL); drsParentByImport = dtParents.Select("IsImport=1"); drsParentByInput = dtParents.Select("IsImport=0"); strUsername = (dtStudent.Rows.Count > 0) ? dtStudent.Rows[0]["Username"].ToString() : ""; strStudentName = (dtStudent.Rows.Count > 0) ? dtStudent.Rows[0]["FullName"].ToString() : ""; #endregion Initialize Values and Form Execution #region Properties For The State Base Class TitleBar = "Parent/Guardian Access Accounts"; SubTitleBar = "Parent/Guardian Access Accounts"; #endregion Properties For The State Base Class }
private string criaArquivoLog(System.Data.DataTable pTabelaArquivo, string pNomeArquivo) { string iContrato = ""; string iContratoAnterior = ""; int iOrdenador = 0; foreach (System.Data.DataRow iLinha in pTabelaArquivo.Select("", "NumeroContrato asc")) { iContrato = iLinha["numeroContrato"].ToString(); if (iContrato != iContratoAnterior && iContratoAnterior != "") { iOrdenador = pTabelaArquivo.Select("NumeroContrato = '" + iContratoAnterior + "'").Length + 1; pTabelaArquivo.Rows.Add(new object[] { iOrdenador, iContratoAnterior, "--", "", "" }); pTabelaArquivo.Rows.Add(new object[] { iOrdenador + 1, iContratoAnterior, "--------------------", "--------------------", "--------------------" }); pTabelaArquivo.Rows.Add(new object[] { iOrdenador + 2, iContratoAnterior, "--", "", "" }); } iContratoAnterior = iContrato; } // \\10.0.0.210\arb\Baixas bancárias\Débito automático string iDiretorio = @"E:\Baixas - Resultado\Débito automático\" + pNomeArquivo; CarSystem.Utilidades.IO.Arquivo.isExisteDir(iDiretorio, true); string iArquivo = iDiretorio + @"\LOG_" + DateTime.Today.ToString("ddMMyyyy") + "_" + pNomeArquivo + ".log"; CarSystem.Utilidades.IO.Arquivo.sqlTOtxt(pTabelaArquivo.Select("", "NumeroContrato asc, Ordem asc"), iArquivo, true); CarSystem.Utilidades.IO.Arquivo.fechaEscritor(); return(iArquivo); }
private void BindBarChart() { zgSales.Visible = false; bcSales.Visible = true; if (salesByMonthData == null) { salesByMonthData = CommerceReport.GetSalesByYearMonthByModule(moduleGuid); } StringBuilder categories = new StringBuilder(); string comma = string.Empty; List <decimal> revenue = new List <decimal>(); // original data is sorted descending on Y, M resorting here DataRow[] result = salesByMonthData.Select(string.Empty, "Y ASC, M ASC"); int spaceInterval = 0; int totalItems = result.Length; int itemsAdded = 0; if (totalItems > 12) { spaceInterval = 4; } int nextItemToShow = 0; foreach (DataRow row in result) { categories.Append(comma); if (itemsAdded == nextItemToShow) { categories.Append(row["Y"].ToString()); categories.Append("-"); categories.Append(row["M"].ToString()); nextItemToShow = itemsAdded + spaceInterval; } comma = ","; revenue.Add(Convert.ToDecimal(row["Sales"])); itemsAdded += 1; } bcSales.ChartTitle = Resource.SalesByMonthChartLabel; bcSales.CategoriesAxis = categories.ToString(); BarChartSeries series = new BarChartSeries(); //series.Name = Resource.SalesByMonthChartSalesLabel; series.Data = revenue.ToArray(); bcSales.Series.Add(series); //bcSales.CategoriesAxis //bcSales.Series. }
protected void tbnGenerateReport_Click(object sender, EventArgs e) { DataTable dtProductData = new DataTable(); var url = ""; if (ddlSelectProduct.SelectedValue == "0") { url = "https://www.kimonolabs.com/api/du33b7qw?apikey=rIUTL1gnwlZf0c0S8aDdLfGpMPGblfhN"; // Venom } else if (ddlSelectProduct.SelectedValue == "1") { url = "https://www.kimonolabs.com/api/biu6l4c8?&apikey=rIUTL1gnwlZf0c0S8aDdLfGpMPGblfhN"; // Optimum Whey } else if (ddlSelectProduct.SelectedValue == "2") { url = "https://www.kimonolabs.com/api/7qpe5n4g?&apikey=rIUTL1gnwlZf0c0S8aDdLfGpMPGblfhN"; // Pea Protein } else if (ddlSelectProduct.SelectedValue == "3") { url = "https://www.kimonolabs.com/api/87yhw5ha?&apikey=rIUTL1gnwlZf0c0S8aDdLfGpMPGblfhN"; // Nutrients Direct Whey Protein } else if (ddlSelectProduct.SelectedValue == "4") { url = "https://www.kimonolabs.com/api/adx2qlak?&apikey=rIUTL1gnwlZf0c0S8aDdLfGpMPGblfhN"; // Swisse Men’s Ultivite } else if (ddlSelectProduct.SelectedValue == "5") { url = "https://www.kimonolabs.com/api/5161uvtw?&apikey=rIUTL1gnwlZf0c0S8aDdLfGpMPGblfhN"; // Beagle Telecom } else if (ddlSelectProduct.SelectedValue == "6") { url = "https://www.kimonolabs.com/api/4t9u4z0y?&apikey=rIUTL1gnwlZf0c0S8aDdLfGpMPGblfhN"; // Bigpond } dtProductData = Review.GetDataFromURL(url); ProductDetails.Visible = true; CommentDetails.Visible = true; lblProductName.Text = dtProductData.Rows[0]["ProductName"].ToString(); lblAverageRatings.Text = dtProductData.Rows[0]["AverageRating"].ToString(); lblTotalRating.Text = dtProductData.Rows[0]["OutofRating"].ToString(); int PositiveCount = dtProductData.Select("Interpretation = 'Positive'").Length; int NegativeCount = dtProductData.Select("Interpretation = 'Negative'").Length; int UndCount = dtProductData.Select("Interpretation = 'Undetermined'").Length; int TotalCount = dtProductData.Rows.Count; lblPositiveComments.Text = PositiveCount + "/" + TotalCount; lblNegativeComments.Text = NegativeCount + "/" + TotalCount; lblUndComments.Text = UndCount + "/" + TotalCount; StringBuilder objStringBuilder = RenderGrid(dtProductData); divResult.InnerHtml = objStringBuilder.ToString(); }
/// <summary> /// 得到角色应用JSON /// </summary> /// <param name="roleID"></param> /// <returns></returns> public string GetRoleAppJsonString(Guid roleID) { Business.Platform.RoleApp RoleApp = new Business.Platform.RoleApp(); System.Data.DataTable appDt = RoleApp.GetAllDataTableFromCache(); if (appDt.Rows.Count == 0) { return("[]"); } var root = appDt.Select(string.Format("ParentID='{0}' AND RoleID='{1}'", Guid.Empty.ToString(), roleID)); if (root.Length == 0) { return("[]"); } var apps = appDt.Select(string.Format("ParentID='{0}'", root[0]["ID"].ToString())); System.Text.StringBuilder json = new System.Text.StringBuilder("[", 1000); System.Data.DataRow rootDr = root[0]; json.Append("{"); json.AppendFormat("\"id\":\"{0}\",", rootDr["ID"]); json.AppendFormat("\"title\":\"{0}\",", rootDr["Title"].ToString().Trim()); json.AppendFormat("\"ico\":\"{0}\",", ""); json.AppendFormat("\"link\":\"{0}\",", getAddress(rootDr)); json.AppendFormat("\"model\":\"{0}\",", rootDr["OpenMode"]); json.AppendFormat("\"width\":\"{0}\",", rootDr["Width"]); json.AppendFormat("\"height\":\"{0}\",", rootDr["Height"]); json.AppendFormat("\"hasChilds\":\"{0}\",", apps.Length > 0 ? "1" : "0"); json.AppendFormat("\"childs\":["); for (int i = 0; i < apps.Length; i++) { DataRow dr = apps[i]; var childs = appDt.Select("ParentID='" + dr["ID"].ToString() + "'"); json.Append("{"); json.AppendFormat("\"id\":\"{0}\",", dr["ID"]); json.AppendFormat("\"title\":\"{0}\",", dr["Title"]); json.AppendFormat("\"ico\":\"{0}\",", ""); json.AppendFormat("\"link\":\"{0}\",", getAddress(rootDr)); json.AppendFormat("\"model\":\"{0}\",", dr["OpenMode"]); json.AppendFormat("\"width\":\"{0}\",", dr["Width"]); json.AppendFormat("\"height\":\"{0}\",", dr["Height"]); json.AppendFormat("\"hasChilds\":\"{0}\",", childs.Length > 0 ? "1" : "0"); json.AppendFormat("\"childs\":["); json.Append("]"); json.Append("}"); if (i < apps.Length - 1) { json.Append(","); } } json.Append("]"); json.Append("}"); json.Append("]"); return(json.ToString()); }
void _province1_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (_province1.SelectedIndex > 0) { DataRow[] rows = ProvinceCityTable.Select("pid = '" + (_province1.SelectedItem as System.Windows.Controls.Label).Tag.ToString() + "'"); ComboboxTool.InitComboboxSource(_city1, rows, "cxtj"); //20150707被检单位改为连动(受来源产地影响) ComboboxTool.InitComboboxSource(_source_company1, string.Format(" call p_user_company('{0}','{1}') ", userId, (_province1.SelectedItem as System.Windows.Controls.Label).Tag.ToString()), "cxtj"); _city1.SelectionChanged += new SelectionChangedEventHandler(_city1_SelectionChanged); } }
private int createTable_Oracle(BizProcess.Data.Model.DBExtract dbe) { System.Text.StringBuilder sql = new System.Text.StringBuilder(); sql.AppendFormat("CREATE TABLE {0}(", dbe.Name); //sql.AppendFormat("", dbe.Comment); var jsonData = LitJson.JsonMapper.ToObject(dbe.DesignJSON); BizProcess.Platform.DBConnection bdbConn = new BizProcess.Platform.DBConnection(); BizProcess.Data.Model.DBConnection conn = bdbConn.Get(dbe.DBConnID); using (System.Data.IDbConnection iconn = bdbConn.GetConnection(conn)) { try { if (iconn.State == ConnectionState.Closed) { iconn.Open(); } System.Data.DataTable schemaDt = bdbConn.GetTableSchema(iconn, jsonData["table"].ToString(), conn.Type); //primary key field string fieldname = jsonData["primarykey"].ToString(); System.Data.DataRow[] schemaDrs = schemaDt.Select(string.Format("f_name='{0}'", fieldname)); if (schemaDrs.Length == 0) { return(0); } sql.Append(getFieldString_Oracle(schemaDrs)); //fields var fields = LitJson.JsonMapper.ToObject(jsonData["fields"].ToJson()); foreach (LitJson.JsonData field in fields) { fieldname = field["field"].ToString(); schemaDrs = schemaDt.Select(string.Format("f_name='{0}'", fieldname)); if (schemaDrs.Length == 0) { return(0); } sql.Append(getFieldString_Oracle(schemaDrs)); } sql.AppendFormat("CONSTRAINT {0}_pk PRIMARY KEY ({1}))", dbe.Name, jsonData["primarykey"].ToString()); } catch (OracleException ex) { } } //create table into the system database return(dataDBExtract.ExecuteStatement(sql.ToString())); }
private int createTable_SqlServer(BizProcess.Data.Model.DBExtract dbe) { System.Text.StringBuilder sql = new System.Text.StringBuilder(); sql.AppendFormat("CREATE TABLE {0}(", dbe.Name); //sql.AppendFormat("", dbe.Comment); var jsonData = LitJson.JsonMapper.ToObject(dbe.DesignJSON); BizProcess.Platform.DBConnection bdbConn = new BizProcess.Platform.DBConnection(); BizProcess.Data.Model.DBConnection conn = bdbConn.Get(dbe.DBConnID); using (System.Data.IDbConnection iconn = bdbConn.GetConnection(conn)) { try { if (iconn.State == ConnectionState.Closed) { iconn.Open(); } System.Data.DataTable schemaDt = bdbConn.GetTableSchema(iconn, jsonData["table"].ToString(), conn.Type); //primary key field string fieldname = jsonData["primarykey"].ToString(); System.Data.DataRow[] schemaDrs = schemaDt.Select(string.Format("f_name='{0}'", fieldname)); if (schemaDrs.Length == 0) { return(0); } sql.Append(getFieldString_SqlServer(schemaDrs)); //fields var fields = LitJson.JsonMapper.ToObject(jsonData["fields"].ToJson()); foreach (LitJson.JsonData field in fields) { fieldname = field["field"].ToString(); schemaDrs = schemaDt.Select(string.Format("f_name='{0}'", fieldname)); if (schemaDrs.Length == 0) { return(0); } sql.Append(getFieldString_SqlServer(schemaDrs)); } sql.AppendFormat("CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED ([{1}] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]", dbe.Name, jsonData["primarykey"].ToString()); } catch (SqlException ex) { } } //create table into the system database return(dataDBExtract.ExecuteStatement(sql.ToString())); }
private void OnSubmit(object sender, EventArgs e)//提交代码处理 { try { System.Data.DataTable temp_dt = dt_fault.Copy(); for (int index = 0; index < dt_fault.Rows.Count; index++) { string str_fault = dt_fault.Rows[index]["故障"] as string; for (int i = 0; i < dt_symptom.Rows.Count; i++) { if (matrix[i, index] == 1)//规则1必要性检测 { if ((bool)dt_symptom.Rows[i]["isChecked"] == false) { DataRow[] rows = temp_dt.Select("故障='" + str_fault + "'"); if (rows.Count() == 1) { temp_dt.Rows.Remove(rows[0]); continue; } else if (rows.Count() > 1) { throw new Exception("故障名称重复"); } } } if (matrix[i, index] == -1)//规则3充分性检测 { if ((bool)dt_symptom.Rows[i]["isChecked"] == true) { DataRow[] rows = temp_dt.Select("故障='" + str_fault + "'"); if (rows.Count() == 1) { temp_dt.Rows.Remove(rows[0]); continue; } else if (rows.Count() > 1) { throw new Exception("故障名称重复"); } } } } } dataResult.DataSource = temp_dt; // temp_dt.Rows. } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void Print(DataTable barcodeTable) { DataRow[] barcodeRows = barcodeTable.Select("ISMIX='0'", "BARCODEORDER"); foreach (DataRow row in barcodeRows) { barcodeRow = row; if (row["MIXID"].ToString().Trim().Length != 0) mixRows = barcodeTable.Select(String.Format("MIXID='{0}' AND ISMIX='1'", row["MIXID"])); else mixRows = null; printDoc.Print(); } }
public void Print(DataTable barcodeTable, string barcode) { DataRow[] barcodeRows = barcodeTable.Select(string.Format("BARCODE='{0}'", barcode)); if (barcodeRows.Length != 0) { barcodeRow = barcodeRows[0]; if (barcodeRows[0]["MIXID"].ToString().Trim().Length != 0) mixRows = barcodeTable.Select(String.Format("MIXID='{0}' AND ISMIX='1'", barcodeRows[0]["MIXID"])); else mixRows = null; printDoc.Print(); } }
private static void FilterData(DataTable emps, DataTable jobs, string resType) { //notice that except for resType = ASSIGNED and jobType = All, these filters //all depends on both JobId and Userid data because all of these look at the //allocations table, whose rows include jobid, userid fields. //restypes are: ASSIGNED, ALLOCATED, UNALLOCATED, OVERALLOCATED, UNDERALLOCATED long start = DateTime.Now.Ticks; ArrayList toRemove = new ArrayList(); DataRow[] rows = null; //filter for "Allocated" jobs foreach (DataRow row in jobs.Rows) { int job = Convert.ToInt32(row["JobId"]); rows = emps.Select("JobId=" + job + " AND AnyMins>0"); if (rows.Length == 0) toRemove.Add(row); } if (toRemove.Count > 0) foreach (object row in toRemove) jobs.Rows.Remove((DataRow)row); switch (resType) { case "ALLOCATED": rows = emps.Select("HrsAllocated<=0 AND RealPerson='Y'"); foreach (DataRow row in rows) emps.Rows.Remove(row); break; case "UNALLOCATED": rows = emps.Select("HrsAllocated>0 AND RealPerson='Y'"); foreach (DataRow row in rows) emps.Rows.Remove(row); break; case "OVERALLOCATED": rows = emps.Select("HrsAllocated < (HrsAvailable*60) AND RealPerson='Y'"); foreach (DataRow row in rows) emps.Rows.Remove(row); break; case "UNDERALLOCATED": //only show ppl who are allocd less hrs than their max rows = emps.Select("HrsAllocated > (HrsAvailable*60) AND RealPerson='Y'"); foreach (DataRow row in rows) emps.Rows.Remove(row); break; } long end = DateTime.Now.Ticks; Debug.WriteLine("filterdata() in deptgrid took: " + (end - start).ToString("n") + " ticks"); }
private string BuildMenuJasonString(DataTable dtMenus) { StringBuilder menuBuilder = new StringBuilder(); string formater = string.Empty; menuBuilder.Append(@"{ 'menus': ["); //分两级菜单,第一级为模块名,第二级为页面菜单 //1. 首先获取模块名,根据排序字段进行升序排序 DataRow[] drRoots = dtMenus.Select("PARENT_ID is NULL", "SORTINDEX ASC"); //2. 遍历模块,获取模块下面的页面菜单。并将页面菜单进行升序排序 int rootIndex = 0; foreach (DataRow dr in drRoots) { rootIndex++; //模块ID string rootID = dr["SORTINDEX"].ToString(); //模块图片路径,如果未设置,则设置默认的图片 string rootIconUrl = dr["ICONURL"].ToString().Trim().Length == 0 ? "icon-sys" : dr["ICONURL"].ToString().Trim(); //模块名 string rootMenuName = dr["TITLE"].ToString(); formater = @"{ 'menuid': '" + rootID + "', 'icon': '" + rootIconUrl + "', 'menuname': '" + rootMenuName + "', 'menus': ["; menuBuilder.Append(formater); string parentID = dr["PK_ID"].ToString(); DataRow[] drMenus = dtMenus.Select("PARENT_ID='" + parentID + "'", "SORTINDEX ASC"); int menuIndex = 0; foreach (DataRow drMenu in drMenus) { menuIndex++; //菜单ID string menuID = drMenu["SORTINDEX"].ToString(); //菜单图片路径,如果未设置,则设置默认的图片 string menuIconUrl = drMenu["ICONURL"].ToString().Trim().Length == 0 ? "icon-nav" : drMenu["ICONURL"].ToString().Trim(); //菜单名 string menuName = drMenu["TITLE"].ToString(); //菜单对应页面路径 string menuPageURL = drMenu["PAGEURL"].ToString().ToLower().Replace("~/pages",".."); if (menuIndex < drMenus.Length) formater = @"{ 'menuid': '" + menuID + "', 'icon': '" + menuIconUrl + "', 'menuname': '" + menuName + "', 'url': '" + menuPageURL + "'},"; else formater = @"{ 'menuid': '" + menuID + "', 'icon': '" + menuIconUrl + "', 'menuname': '" + menuName + "', 'url': '" + menuPageURL + "'}]}"; menuBuilder.Append(formater); } if (rootIndex < drRoots.Length) menuBuilder.Append(","); else menuBuilder.Append("]}"); } return menuBuilder.ToString(); }
/// <summary> /// Divide un campo (per tutte le righe di mData) prendendo quello che viene prima del separatore /// </summary> /// <param name="fieldOriginal">Nome del campo originale</param> /// <param name="fieldDescr">Nome del campo dove finisce la descrizione - parametro ad oggi inutile</param> /// <param name="separatore">Carattere di separazione</param> /// <returns></returns> private bool split_descrizione(string fieldOriginal, string fieldDescr, string separatore) { string operazione = ""; switch (fieldOriginal) { case "CAPITOLO": { operazione = "Split descrizione del capitolo"; break; } case "RUOLO": { operazione = "Split descrizione del ruolo"; break; } case "ENTE": { operazione = "Split descrizione dell'ente"; break; } case "VOCE": { operazione = "Split descrizione della voce"; break; } } lblTask.Text = operazione; progressBar1.Value = 0; progressBar1.Maximum = mData.Rows.Count; foreach (System.Data.DataRow r in mData.Select()) { progressBar1.Value++; System.Windows.Forms.Application.DoEvents(); if (r[fieldOriginal] == DBNull.Value) { continue; } string capitolo = r[fieldOriginal].ToString(); int indice = capitolo.IndexOf(separatore); if (indice == -1) { continue; } string descrizione = capitolo.Remove(0, indice + 1); string codice = capitolo.Remove(indice, capitolo.Length - indice); r[fieldOriginal] = codice; //r[fieldDescr] = descrizione; } return(true); }
private void InitialisePaymentLimits() { string strProcessCode = string.Empty; string strProcessText = string.Empty; string strMinLimit = string.Empty; string strMaxLimit = string.Empty; string strTotalAllowed = string.Empty; string strDailyLimit = string.Empty; string strMethodId = string.Empty; System.Data.DataTable dtPaymentMethodLimits = null; System.Data.DataRow drPaymentMethodLimit = null; System.Text.StringBuilder sbMethodsUnavailable = new System.Text.StringBuilder(); strMethodId = "0"; using (svcPayMember.MemberClient svcInstance = new svcPayMember.MemberClient()) { dtPaymentMethodLimits = svcInstance.getMethodLimits(strOperatorId, strMemberCode, strMethodId, Convert.ToString(Convert.ToInt32(commonVariables.PaymentTransactionType.Withdrawal)), false, out strProcessCode, out strProcessText); } foreach (commonVariables.WithdrawalMethod EnumMethod in Enum.GetValues(typeof(commonVariables.WithdrawalMethod))) { if (dtPaymentMethodLimits.Select("[methodId] = " + Convert.ToInt32(EnumMethod)).Count() < 1) { sbMethodsUnavailable.AppendFormat("{0}|", Convert.ToInt32(EnumMethod)); } } strMethodId = Convert.ToString(Convert.ToInt32(commonVariables.WithdrawalMethod.BankTransfer)); if (dtPaymentMethodLimits.Select("[methodId] = " + strMethodId).Count() > 0) { drPaymentMethodLimit = dtPaymentMethodLimits.Select("[methodId] = " + strMethodId)[0]; strMinLimit = Convert.ToDecimal(dtPaymentMethodLimits.Rows[0]["minDeposit"]).ToString(commonVariables.DecimalFormat); strMaxLimit = Convert.ToDecimal(dtPaymentMethodLimits.Rows[0]["maxDeposit"]).ToString(commonVariables.DecimalFormat); strTotalAllowed = Convert.ToDecimal(dtPaymentMethodLimits.Rows[0]["totalAllowed"]).ToString(commonVariables.DecimalFormat); strDailyLimit = Convert.ToDecimal(dtPaymentMethodLimits.Rows[0]["limitDaily"]).ToString(commonVariables.DecimalFormat); //txtAmount.Attributes.Add("PLACEHOLDER", string.Format("{0} {1}({2} / {3})", lblAmount.Text, strCurrencyCode, strMinLimit, strMaxLimit)); lblDailyLimit.InnerText = string.Format("{0} {1}", commonCulture.ElementValues.getResourceString("lblDailyLimit", xeResources), strDailyLimit); lblTotalAllowed.InnerText = string.Format("{0} {1}", commonCulture.ElementValues.getResourceString("lblTotalAllowed", xeResources), strTotalAllowed); } //else { } strMethodsUnAvailable = Convert.ToString(sbMethodsUnavailable).TrimEnd('|'); }
public Bitmap GetSkillPanelBmp(ref DataTable skillTable, int characterClassId, bool forceRecreate) { _skillTable = skillTable; int generalSkillTableId = 0; string folder = Directory.GetCurrentDirectory() + @"\images\"; string bmpPath = folder + characterClassId + ".bmp"; string select = "skillTab = '" + characterClassId + "'"; DataRow[] skills = _skillTable.Select(select); select = "skillTab = '" + generalSkillTableId + "'"; DataRow[] generalSkills = _skillTable.Select(select); if (!File.Exists(bmpPath) || forceRecreate) { if(!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } //Bitmap classSkillPanel = new Bitmap(_size.Width, _size.Height); Bitmap classSkillPanel = new Bitmap(_unscaledSize.Width, _unscaledSize.Height); Graphics g = Graphics.FromImage(classSkillPanel); g.Clear(Color.Transparent); Bitmap connectorLns = CreateConnectorLines(skills); Bitmap generalSkl = CreateGeneralSkills(generalSkills); Bitmap classSkl = CreateClassSkills(skills); g.DrawImage(connectorLns, new Point()); g.DrawImage(generalSkl, new Point()); g.DrawImage(classSkl, new Point()); classSkillPanel = ReScaleBitmap(classSkillPanel, 802, 746); classSkillPanel.Save(bmpPath); g.Dispose(); } else { CreateGeneralSkills(generalSkills); CreateClassSkills(skills); } return (Bitmap)Bitmap.FromFile(bmpPath); }
private void UpdateUserList() { dtUserTable.Clear(); daUser.Fill(dtUserTable); cmbUser.DataSource = dtUserTable; cmbUser.DisplayMember = "F_PersonLongName"; cmbUser.ValueMember = "F_PersonID"; DataRow[] drSelRows = dtUserTable.Select(String.Format("F_PersonID = {0}", cmbUser.SelectedValue)); if (drSelRows.Length > 0) { strUserPassword = drSelRows[0]["F_PassWord"].ToString(); } }
public static DataTable SelectDistinct(DataTable SourceTable, params string[] FieldNames) { object[] lastValues; DataTable newTable; DataRow[] orderedRows; if (FieldNames == null || FieldNames.Length == 0) throw new ArgumentNullException("FieldNames"); lastValues = new object[FieldNames.Length]; newTable = new DataTable(); foreach (string fieldName in FieldNames) newTable.Columns.Add(fieldName, SourceTable.Columns[fieldName].DataType); orderedRows = SourceTable.Select("", string.Join(", ", FieldNames)); foreach (DataRow row in orderedRows) { if (!fieldValuesAreEqual(lastValues, row, FieldNames)) { newTable.Rows.Add(createRowClone(row, newTable.NewRow(), FieldNames)); setLastValues(lastValues, row, FieldNames); } } return newTable; }
public System.Data.DataTable QueryTable() { if (OleConn == null) { return(null); } try { Object [] ob = new object[] { null, null, null, "TABLE" }; System.Data.DataTable schemaTable = OleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, ob); int i = ob.Length; DataRow[] dr = schemaTable.Select("1=1"); return(schemaTable); } catch (Exception err) { MessageBox.Show("解析excel文件页面失败!失败原因:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return(null); } return(null); }
/// <summary> /// 关联两表HIS价表和EXAM_VS_CHARGE取得数据集并填充Datatable /// </summary> public System.Data.DataTable Bind_ExamVsCharge_His(System.Data.DataTable dt_CurrentPriceList) { BExamVsCharge bExamVsCharge = new BExamVsCharge(); System.Data.DataTable dt = new System.Data.DataTable(); System.Data.DataTable dt_ExamVsCharge = bExamVsCharge.GetList("1=1"); int i = 0; dt.Columns.Add(new System.Data.DataColumn("CLASS_NAME", dt_CurrentPriceList.Columns["CLASS_NAME"].DataType)); dt.Columns.Add(new System.Data.DataColumn("ITEM_CLASS", dt_CurrentPriceList.Columns["ITEM_CLASS"].DataType)); dt.Columns.Add(new System.Data.DataColumn("ITEM_NAME", dt_CurrentPriceList.Columns["ITEM_NAME"].DataType)); dt.Columns.Add(new System.Data.DataColumn("ITEM_SPEC", dt_CurrentPriceList.Columns["ITEM_SPEC"].DataType)); dt.Columns.Add(new System.Data.DataColumn("AMOUNT", dt_ExamVsCharge.Columns["AMOUNT"].DataType)); dt.Columns.Add(new System.Data.DataColumn("UNITS", dt_CurrentPriceList.Columns["UNITS"].DataType)); dt.Columns.Add(new System.Data.DataColumn("PRICE", dt_CurrentPriceList.Columns["PRICE"].DataType)); dt.Columns.Add(new System.Data.DataColumn("EXAM_ITEM_CODE", dt_ExamVsCharge.Columns["EXAM_ITEM_CODE"].DataType)); dt.Columns.Add(new System.Data.DataColumn("ITEM_CODE", dt_CurrentPriceList.Columns["ITEM_CODE"].DataType)); dt.Columns.Add(new System.Data.DataColumn("COSTS", dt_CurrentPriceList.Columns["PRICE"].DataType)); dt.Columns.Add(new System.Data.DataColumn("CHARGES", dt_CurrentPriceList.Columns["PRICE"].DataType)); dt.Columns.Add(new System.Data.DataColumn("CHARGE_ITEM_NO", dt_ExamVsCharge.Columns["CHARGE_ITEM_NO"].DataType)); dt.Columns.Add(new System.Data.DataColumn("INPUT_CODE", dt_CurrentPriceList.Columns["INPUT_CODE"].DataType)); System.Data.DataRow[] Rows; for (i = 0; i < dt_ExamVsCharge.Rows.Count; i++) { Rows = dt_CurrentPriceList.Select("ITEM_CODE='" + dt_ExamVsCharge.Rows[i]["CHARGE_ITEM_CODE"].ToString() + "' and ITEM_SPEC = '" + dt_ExamVsCharge.Rows[i]["CHARGE_ITEM_SPEC"].ToString() + "' and UNITS ='" + dt_ExamVsCharge.Rows[i]["UNITS"].ToString() + "'"); foreach (System.Data.DataRow drow in Rows) { decimal amount = dt_ExamVsCharge.Rows[i]["AMOUNT"].ToString() == "" ? 0 : decimal.Parse(dt_ExamVsCharge.Rows[i]["AMOUNT"].ToString()); decimal costs = amount * decimal.Parse(drow["PRICE"].ToString()); dt.Rows.Add(new object[] { drow["CLASS_NAME"], drow["ITEM_CLASS"], drow["ITEM_NAME"], drow["ITEM_SPEC"], dt_ExamVsCharge.Rows[i]["AMOUNT"], drow["UNITS"], drow["PRICE"], dt_ExamVsCharge.Rows[i]["EXAM_ITEM_CODE"], drow["ITEM_CODE"], costs, costs, dt_ExamVsCharge.Rows[i]["CHARGE_ITEM_NO"], drow["INPUT_CODE"] }); } } return(dt); }
public static string TableToEasyUITreeJson(DataTable dt, string pField, string pValue, string kField, string TextField) { StringBuilder sb = new StringBuilder(); string filter = String.Format(" {0}='{1}' ", pField, pValue);//获取顶级目录. DataRow[] drs = dt.Select(filter); if (drs.Length < 1) return ""; sb.Append(",\"children\":["); foreach (DataRow dr in drs) { string pcv = dr[kField].ToString(); sb.Append("{"); sb.AppendFormat("\"id\":\"{0}\",", dr[kField].ToString()); sb.AppendFormat("\"text\":\"{0}\"", dr[TextField].ToString()); sb.Append(TableToEasyUITreeJson(dt, pField, pcv, kField, TextField).TrimEnd(',')); sb.Append("},"); } if (sb.ToString().EndsWith(",")) { sb.Remove(sb.Length - 1, 1); } sb.Append("]"); return sb.ToString(); }
//�����ڵ� public void CreateNode(int parentid, Microsoft.Web.UI.WebControls.TreeNode parentnode, DataTable dt) { DataRow[] drs = dt.Select("ParentID= " + parentid);//ѡ�������ӽڵ� foreach (DataRow r in drs) { string nodeid = r["NodeID"].ToString(); string text = r["Text"].ToString(); string location = r["Location"].ToString(); string url = r["Url"].ToString(); string imageurl = r["ImageUrl"].ToString(); int permissionid = int.Parse(r["PermissionID"].ToString().Trim()); Microsoft.Web.UI.WebControls.TreeNode node = new Microsoft.Web.UI.WebControls.TreeNode(); node.Text = text + " <a href=\"modify.aspx?id=" + nodeid + "\">��</a> " + " <a onClick=\"if (!window.confirm('�����Ҫɾ��������¼��')){return false;}\" href=\"delete.aspx?id=" + nodeid + "\">ɾ��</a>" + " <a href=\"add.aspx?nodeid="+nodeid+"\">���ӽڵ�</a>"; node.NodeData = nodeid; //node.NavigateUrl = url; //node.Target = TargetFrame; node.ImageUrl = "../" + imageurl; node.Expanded = false; int sonparentid = int.Parse(nodeid);// or =location if (parentnode == null) { TreeView1.Nodes.Clear(); parentnode = new Microsoft.Web.UI.WebControls.TreeNode(); TreeView1.Nodes.Add(parentnode); } parentnode.Nodes.Add(node); CreateNode(sonparentid, node, dt); }//endforeach }
public SysNewDetectScQuery(IDBOperation dbOperation) { InitializeComponent(); this.dbOperation = dbOperation; ProvinceCityTable = Application.Current.Resources["省市表"] as DataTable; DataRow[] rows = ProvinceCityTable.Select("pid = '0001'"); //画面初始化-检测单列表画面 dtpStartDate.SelectedDate= DateTime.Now.AddDays(-1); dtpEndDate.SelectedDate = DateTime.Now; ComboboxTool.InitComboboxSource(_source_company1, string.Format(" call p_user_company('{0}','') ", userId), "cxtj"); ComboboxTool.InitComboboxSource(_detect_station, string.Format("call p_user_dept('{0}','{1}')", userId,"0"), "cxtj"); ComboboxTool.InitComboboxSource(_detect_item1, "SELECT ItemID,ItemNAME FROM t_det_item WHERE OPENFLAG = '1' order by orderId", "cxtj"); ComboboxTool.InitComboboxSource(_detect_object1, "SELECT objectId,objectName FROM t_det_object WHERE OPENFLAG = '1'", "cxtj"); ComboboxTool.InitComboboxSource(_detect_result1, "SELECT resultId,resultName FROM t_det_result where openFlag = '1' ORDER BY id", "cxtj"); ComboboxTool.InitComboboxSource(_detect_person1, string.Format("call p_user_detuser('{0}','{1}')", userId, "0"), "cxtj"); ComboboxTool.InitComboboxSource(_detect_method, "select reagentId,reagentName from t_det_reagent where openFlag = '1'", "cxtj"); ComboboxTool.InitComboboxSource(_detect_type, "SELECT sourceId,sourceName FROM t_det_source where openFlag = '1'", "cxtj"); ComboboxTool.InitComboboxSource(_province1, rows, "cxtj"); _province1.SelectionChanged += new SelectionChangedEventHandler(_province1_SelectionChanged); //20150707检测师改为连动(受监测站点影响) _detect_station.SelectionChanged += new SelectionChangedEventHandler(_detect_station_SelectionChanged); SetColumns(); }
public ArrayList getEERRs() { ArrayList eerrs = new ArrayList(); SQLiteConnection conn = getConnection(); System.Data.DataTable dt = new System.Data.DataTable(); try { SQLiteCommand cmd; //conn.Open(); //Initiate connection to the db cmd = conn.CreateCommand(); cmd.CommandText = QUERY_EERR; //set the passed query ad = new SQLiteDataAdapter(cmd); dt = new System.Data.DataTable(); ad.Fill(dt); //fill the datasource DataRow[] rows = dt.Select(); for (int i = 0; i < rows.Length; i++) { string[] prefix_desc = new string[2]; prefix_desc[0] = (string)rows[i][Constants.EERR_1]; prefix_desc[1] = (string)rows[i][Constants.EERR_2]; eerrs.Add(prefix_desc); } ad.Dispose(); dt.Dispose(); } catch (SQLiteException ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } sqlite = null; return(eerrs); }
private void btnCompararStock_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Benja\\Desktop\\libro1.xlsx;Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\";"; OleDbConnection con = new OleDbConnection(Connection); System.Data.DataTable tblOriginal = new System.Data.DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [original$]", con); myCommand.Fill(tblOriginal); System.Data.DataTable tblModificado = new System.Data.DataTable(); myCommand = new OleDbDataAdapter("select * from [modificado$]", con); myCommand.Fill(tblModificado); int contador = 0; ArrayList miArray = new ArrayList(); foreach (DataRow rowOriginal in tblOriginal.Rows) { string articulo = rowOriginal["Articulo"].ToString(); DataRow[] rowfound = tblModificado.Select("Articulo LIKE '" + articulo + "'"); if (rowfound.Count() == 0) { miArray.Add(articulo); } foreach (DataRow rowModificado in rowfound) { string originalMakro = rowOriginal["Makro"].ToString(); string modificadoMakro = rowModificado["Makro"].ToString(); string originalJesus = rowOriginal["Jesus Maria"].ToString(); string modificadoJesus = rowModificado["Jesus Maria"].ToString(); if (originalMakro != modificadoMakro || originalJesus != modificadoJesus) MessageBox.Show(rowOriginal["Articulo"].ToString()); } contador++; } MessageBox.Show(contador.ToString()); Cursor.Current = Cursors.Arrow; }
/// <summary> /// 递归将DataTable转化为适合jquery easy ui 控件tree ,combotree 的 json /// 该方法最后还要 将结果稍微处理下,将最前面的,"children" 字符去掉. /// </summary> /// <param name="dt">要转化的表</param> /// <param name="pField">表中的父节点字段</param> /// <param name="pValue">表中顶层节点的值,没有 可以输入为0</param> /// <param name="kField">关键字字段名称</param> /// <param name="TextField">要显示的文本 对应的字段</param> /// <returns></returns> public static string TableToEasyUITreeJson(System.Data.DataTable dt, string pField, string pValue, string kField, string TextField) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); string filter = String.Format(" {0}='{1}' ", pField, pValue);//获取顶级目录. System.Data.DataRow[] drs = dt.Select(filter); if (drs.Length < 1) { return(""); } sb.Append(",\"children\":["); foreach (System.Data.DataRow dr in drs) { string pcv = dr[kField].ToString(); sb.Append("{"); sb.AppendFormat("\"id\":\"{0}\",", dr[kField].ToString()); sb.AppendFormat("\"text\":\"{0}\"", dr[TextField].ToString()); sb.Append(TableToEasyUITreeJson(dt, pField, pcv, kField, TextField).TrimEnd(',')); sb.Append("},"); } if (sb.ToString().EndsWith(",")) { sb.Remove(sb.Length - 1, 1); } sb.Append("]"); return(sb.ToString()); }
public Dictionary <string, string[]> getAreas() { Dictionary <string, string[]> areas = new Dictionary <string, string[]>(); SQLiteConnection conn = getConnection(); System.Data.DataTable dt = new System.Data.DataTable(); try { SQLiteCommand cmd; //conn.Open(); //Initiate connection to the db cmd = conn.CreateCommand(); cmd.CommandText = QUERY_AREA; ad = new SQLiteDataAdapter(cmd); dt = new System.Data.DataTable(); ad.Fill(dt); //fill the datasource DataRow[] rows = dt.Select(); for (int i = 0; i < rows.Length; i++) { string[] marca_agrup = new string[2]; marca_agrup[0] = (string)rows[i][Constants.AREA_2]; marca_agrup[1] = (string)rows[i][Constants.AREA_3]; areas.Add((string)rows[i][Constants.AREA_1], marca_agrup); } ad.Dispose(); dt.Dispose(); } catch (SQLiteException ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } sqlite = null; return(areas); }
public SysDetectReport(IDBOperation dbOperation) { InitializeComponent(); this.dbOperation = dbOperation; ProvinceCityTable = System.Windows.Application.Current.Resources["省市表"] as System.Data.DataTable; DataRow[] rows = ProvinceCityTable.Select("pid = '0001'"); //画面初始化-检测单列表画面 dtpStartDate.SelectedDate = DateTime.Now.AddDays(-1); dtpEndDate.SelectedDate = DateTime.Now; ComboboxTool.InitComboboxSource(_source_company1, string.Format(" call p_user_company('{0}','') ", userId), "cxtj"); ComboboxTool.InitComboboxSource(_detect_station, string.Format("call p_user_dept('{0}')", userId), "cxtj"); ComboboxTool.InitComboboxSource(_detect_person1, string.Format("call p_user_detuser('{0}')", userId), "cxtj"); ComboboxTool.InitComboboxSource(_province1, rows, "cxtj"); _province1.SelectionChanged += new SelectionChangedEventHandler(_province1_SelectionChanged); //20150707检测师改为连动(受监测站点影响) _detect_station.SelectionChanged += new SelectionChangedEventHandler(_detect_station_SelectionChanged); //如果登录用户的部门是站点级别,则将查询条件检测单位赋上默认值 if (user_flag_tier == "4") { _detect_station.SelectedIndex = 1; } }
private void PoiskIn(string familia) { //параметры подключения string sParamConnection = @" Data Source=STAS-PK;Initial Catalog=inkasacia;Integrated Security=SSPI"; SqlConnection connection = new SqlConnection(sParamConnection); connection.Open(); var myTbl = new DataTable(); string sQuery = (@" SELECT Фамилия, Имя, Отчество FROM Sotrudnik"); SqlDataAdapter adapter = new SqlDataAdapter(sQuery, connection); adapter.Fill(myTbl); DataRow[] drArr = myTbl.Select(); //создание курсора foreach (DataRow dr in drArr) { string fam = Convert.ToString(dr.ItemArray[0]); string nam = Convert.ToString(dr.ItemArray[1]); string otche = Convert.ToString(dr.ItemArray[2]); //условие if (familia == fam) { _namee = Convert.ToString(nam[0]); _otche = Convert.ToString(otche[0]); } } }
public static string GetQuestionTest(string ResourceToResourceFolder_Id, string ScoreId) { try { StringBuilder stbHtml = new StringBuilder(); Model_ResourceToResourceFolder model = new Model_ResourceToResourceFolder(); model = new BLL_ResourceToResourceFolder().GetModel(ResourceToResourceFolder_Id); string sqlTest = @"select TestQuestions_Score_ID,S_TestQuestions_TP_ID,TPNameBasic,TPName,tk.CreateTime from [S_TestQuestions_TP] tk inner join [dbo].[S_TestingPoint] sp on sp.S_TestingPoint_Id=tk.S_TestingPoint_Id left join S_TestingPointBasic t on t.S_TestingPointBasic_Id=sp.S_TestingPointBasic_Id where TestQuestions_Score_ID='" + ScoreId + "'"; System.Data.DataTable dtTest = Rc.Common.DBUtility.DbHelperSQL.Query(sqlTest).Tables[0]; System.Data.DataRow[] drAttr = dtTest.Select("TestQuestions_Score_ID='" + ScoreId + "'", "CreateTime desc,TPName"); if (drAttr.Length > 0) { foreach (var item in drAttr) { stbHtml.AppendFormat("<span class=\"tag\">{0}<i data-name=\"removeTest\" data-tkid=\"{1}\">×</i></span>", item["TPNameBasic"], item["S_TestQuestions_TP_ID"]); } } if (model != null) { stbHtml.AppendFormat("<span class=\"tag_add\" data-name=\"addTestNew\" data-scoreid=\"{0}\" data-g=\"{1}\" data-s=\"{2}\" data-v=\"{3}\" data-type=\"1\">+</span>" , ScoreId , model.GradeTerm , model.Subject , model.Resource_Version); } return(stbHtml.ToString()); } catch (Exception ex) { return(""); } }
protected void Page_Load(object sender, System.EventArgs e) { MemberInfo currentMember = MemberProcessor.GetCurrentMember(); if (currentMember == null) { base.Response.Write(";"); } else { System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); int userId = currentMember.UserId; NoticeQuery noticeQuery = new NoticeQuery(); noticeQuery.SendType = 0; noticeQuery.UserId = new int?(userId); bool value = DistributorsBrower.GetDistributorInfo(userId) != null; noticeQuery.IsDistributor = new bool?(value); noticeQuery.IsDel = new int?(0); System.Data.DataTable noticeNotReadDt = NoticeBrowser.GetNoticeNotReadDt(noticeQuery); if (noticeNotReadDt != null && noticeNotReadDt.Rows.Count > 0) { System.Data.DataRow[] array = noticeNotReadDt.Select("SendType='0'"); if (array != null) { stringBuilder.Append("$('.my-message').html('<i></i>');"); } else { stringBuilder.Append("$('.my-message').html('<i></i>').attr('href','notice.aspx?type=1');"); } for (int i = 0; i < noticeNotReadDt.Rows.Count; i++) { if (System.Convert.ToInt32(noticeNotReadDt.Rows[i]["SendType"]) == 0) { stringBuilder.Append(string.Concat(new object[] { "$('.new_message ul').append('<li><a href=\"NoticeDetail.aspx?Id=", noticeNotReadDt.Rows[i]["Id"], "\">", noticeNotReadDt.Rows[i]["Title"], "</a></li>');" })); } else { stringBuilder.Append(string.Concat(new object[] { "$('.new_message ul').append('<li><a href=\"NoticeDetail.aspx?Id=", noticeNotReadDt.Rows[i]["Id"], "\">", noticeNotReadDt.Rows[i]["Title"], "</a></li>');" })); } } } base.Response.Write(stringBuilder.ToString()); } base.Response.End(); }
public Dictionary <string, string> getItems() { Dictionary <string, string> items = new Dictionary <string, string>(); SQLiteConnection conn = getConnection(); System.Data.DataTable dt = new System.Data.DataTable(); try { SQLiteCommand cmd; //conn.Open(); //Initiate connection to the db cmd = conn.CreateCommand(); cmd.CommandText = QUERY_ITEMS; ad = new SQLiteDataAdapter(cmd); ad.Fill(dt); //fill the datasource DataRow[] rows = dt.Select(); for (int i = 0; i < rows.Length; i++) { items.Add((string)rows[i][Constants.ITEMS_1], (string)rows[i][Constants.ITEMS_2]); } ad.Dispose(); dt.Dispose(); rows = null; } catch (SQLiteException ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } sqlite = null; return(items); }
/// <summary> /// 获取表数据 /// </summary> /// <param name="startIndex">开始的位置(由0开始)</param> /// <param name="count">要查询的条数(传入0为查全部)</param> /// <param name="select">查询条件</param> /// <param name="dt">DataTable数据集</param> /// <returns>结果集</returns> public static DataTable Select(int startIndex, int count, string select, DataTable dt) { DataRow[] dr = dt.Select(select); int length = startIndex + count; DataTable returndt = dt.Clone(); if (count == 0) { count = dr.Length; } else if (count > dr.Length) { count = dr.Length; } else if (dr.Length < length) { for (int i = startIndex; i < dr.Length; i++) { returndt.ImportRow(dr[i]); } } else { for (int i = startIndex; i < length; i++) { returndt.ImportRow(dr[i]); } } return returndt; }
[Test] public void Generate() { Exception tmpEx = new Exception() ; DataTable tbl = new DataTable(); tbl.Columns.Add(new DataColumn("Column")); DataColumn dc = new DataColumn(); dc.Expression = "something"; //invalid expression // SyntaxErrorException - Column Expression try { tbl.Columns[0].Expression = "Colummn +=+ 1"; //invalid expression Assert.Fail("SEE1: Columns[0].Expression failed to raise SyntaxErrorException."); } catch (SyntaxErrorException) {} catch (AssertionException) { throw; } catch (Exception exc) { Assert.Fail("SEE2: Columns[0].Expression wrong exception type. Got: " + exc); } // SyntaxErrorException - Select try { tbl.Select("Name += bulshit"); Assert.Fail("SEE3: Select failed to raise SyntaxErrorException."); } catch (SyntaxErrorException) {} catch (AssertionException) { throw; } catch (Exception exc) { Assert.Fail("SEE4: Select wrong exception type. Got: " + exc); } }
public static void ExportFilteredDataTableToCsv(DataTable targetDataTable, string targetFilePath, string filterString) { using (System.IO.StreamWriter outFile = new System.IO.StreamWriter(targetFilePath, false, Encoding.UTF8)) { for (int i = 0; i < targetDataTable.Columns.Count; i++) { outFile.Write("\""); outFile.Write(targetDataTable.Columns[i].ColumnName.Replace("\"", "\"\"")); outFile.Write("\""); outFile.Write(i == targetDataTable.Columns.Count - 1 ? Environment.NewLine : ","); } foreach (DataRow row in targetDataTable.Select(filterString)) { for (int i = 0; i < targetDataTable.Columns.Count; i++) { outFile.Write("\""); if (targetDataTable.Columns[i].DataType.Equals(typeof(DateTime))) outFile.Write(FormatDateFullTimeStamp((DateTime)row[i])); else outFile.Write(row[i].ToString().Replace("\"", "\"\"")); outFile.Write("\""); outFile.Write(i == targetDataTable.Columns.Count - 1 ? Environment.NewLine : ","); } } } }
/// <summary> /// Parses the whole excel file and returns the result datatable. /// </summary> /// <param name="file">ExcelFile that contains the raw data.</param> /// <returns></returns> public System.Data.DataTable ParseFile(ExcelFile file) { this.Status = "Getting raw data table..."; this._rawDataTable = file.RawDataTable; this.Status = "Initializing components data table..."; InitComponentsDataTable(_rawDataTable.Columns); this._componentsLookup = new ComponentsLookupBuilder(ComponentsLookupFileName).GetComponentsLookupTable(); for (int i = 0; i < _rawDataTable.Rows.Count; i++) { Component c = ParseRow(_rawDataTable.Rows[i]); c.SerialNumber = (i + 1).ToString(); c.PCB_Name = GetFileName(file.FileName); _componentsDataTable.Rows.Add(c.SerialNumber, c.PCB_Name, c.Type, c.Code, c.SewedyPartNumber, c.PartRef, c.Description, c.Manufacturer, c.Quantity ); } return(_componentsDataTable.Select().OrderBy(u => u["Code"]).CopyToDataTable()); }
/// <summary> /// target focus IDTypeManagement because each ExtKey has one IDTypemanagment /// from IDTypeManagement can search Ads of url page /// </summary> /// <param name="Key"></param> /// <param name="ExtKey"></param> /// <returns></returns> public static int GetInfoKey(DataTable ListKeys, string Key, string ExtKey) { DataRow[] tmp_rows = ListKeys.Select("PriKey = '" + Key + "' AND ExtKey = '" + ExtKey + "'"); if (tmp_rows.Length == 1) return int.Parse(tmp_rows[0]["IDTypeManagement"].ToString()); return -1; }
public async Task getLocation(IDialogContext context, LuisResult result) { var LocationEntity = result.Entities.SingleOrDefault(e => e.Type == "Location"); System.Data.DataTable dtExcel; dtExcel = new System.Data.DataTable(); dtExcel.TableName = "MyExcelData"; string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\\Users\\Sathya\\Pictures\\SCOUT-master\\Dialogs\\lastyeareamcetdata.xlsx';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'"; OleDbConnection con = new OleDbConnection(SourceConstr); string query = "Select * from [Sheet1$]"; OleDbDataAdapter data = new OleDbDataAdapter(query, con); data.Fill(dtExcel); string expression = "Location = '" + LocationEntity.Entity.ToUpper() + "'"; DataRow[] foundRows; // Use the Select method to find all rows matching the filter. foundRows = dtExcel.Select(expression); //Print column 0 of each returned row. string res = ""; for (int i = 0; i < foundRows.Length; i++) { res += foundRows[i][1] + " --- " + foundRows[i][7] + " " + "<br />"; } await context.PostAsync(res); context.Wait(MessageReceived); }
protected void Bind_OTHER_MAR(string ContractNo, string FatherCode) { //获取该合同号下的所有生产制号 //string sql_ENGID = "select PCON_SCH from View_YS_CONTRACT where PCON_BCODE='" + ContractNo + "'"; //System.Data.DataTable dt_ENGID = DBCallCommon.GetDTUsingSqlText(sql_ENGID); //string ENGID = ""; //if (dt_ENGID.Rows.Count > 0) //{ // ENGID = dt_ENGID.Rows[0]["PCON_SCH"].ToString(); //} string ENGID = ContractNo; double total = 0; //总金额 string sql_total = "select YS_" + FatherCode + " from YS_COST_REAL where YS_TSA_ID='" + ContractNo + "'"; System.Data.DataTable dt_total = DBCallCommon.GetDTUsingSqlText(sql_total); if (dt_total.Rows.Count > 0) { total = (dt_total.Rows[0][0].ToString() == "" ? 0 : double.Parse(dt_total.Rows[0][0].ToString())); //总金额 } string sql_OtherMar = "select YS_CODE,YS_NAME,YS_MONEY as YS_MONEY_BG,YS_Union_Amount as YS_Union_Amount_BG," + "YS_Average_Price as YS_Average_Price_BG from YS_COST_BUDGET_DETAIL where YS_TSA_ID='" + ContractNo + "'" + " and YS_FATHER='" + FatherCode + "'"; System.Data.DataTable dt_OtherMar = DBCallCommon.GetDTUsingSqlText(sql_OtherMar); dt_OtherMar.Columns.Add("YS_Union_Amount"); dt_OtherMar.Columns.Add("YS_Average_Price"); dt_OtherMar.Columns.Add("YS_MONEY"); double main_mar = 0; for (int j = 0; j < dt_OtherMar.Rows.Count; j++) { string sql_code = "select sum(Amount) as Amount from View_SM_OUT where TSAID = '" + ENGID + "' AND TSAID != '' and MaterialCode like '" + dt_OtherMar.Rows[j]["YS_CODE"] + "%'"; System.Data.DataTable dt_code = DBCallCommon.GetDTUsingSqlText(sql_code); double money = 0; if (dt_code.Rows.Count > 0) { money = (dt_code.Rows[0]["Amount"].ToString() == "" ? 0 : double.Parse(dt_code.Rows[0]["Amount"].ToString())); } dt_OtherMar.Rows[j]["YS_MONEY"] = money.ToString("F3"); main_mar += money; } double other = total - main_mar; DataRow[] dr = dt_OtherMar.Select("YS_CODE='other'"); //其它费用 for (int i = 0; i < dr.Length; i++) { dr[i]["YS_MONEY"] = other.ToString("F3"); } lbl_total.Text = total.ToString("N2"); GridView1.DataSource = dt_OtherMar; GridView1.DataBind(); GridView1.Columns[3].Visible = false; //单价数量隐藏 GridView1.Columns[4].Visible = false; GridView1.Columns[6].Visible = false; //单价数量隐藏 GridView1.Columns[7].Visible = false; }
public static DataTable SortDataTable(DataTable dt, string sort) { DataTable newDT = dt.Clone(); int rowCount = dt.Rows.Count; DataRow[] foundRows = dt.Select(null, sort); // Sort with Column name for (int i = 0; i < rowCount; i++) { object[] arr = new object[dt.Columns.Count]; for (int j = 0; j < dt.Columns.Count; j++) { arr[j] = foundRows[i][j]; } DataRow data_row = newDT.NewRow(); data_row.ItemArray = arr; newDT.Rows.Add(data_row); } //clear the incoming dt dt.Rows.Clear(); for (int i = 0; i < newDT.Rows.Count; i++) { object[] arr = new object[dt.Columns.Count]; for (int j = 0; j < dt.Columns.Count; j++) { arr[j] = newDT.Rows[i][j]; } DataRow data_row = dt.NewRow(); data_row.ItemArray = arr; dt.Rows.Add(data_row); } return dt; }
private static DbSchemaRow[] GetSortedSchemaRows(DataTable dataTable, bool returnProviderSpecificTypes) { DataColumn column = dataTable.Columns[SchemaMappingUnsortedIndex]; if (column == null) { column = new DataColumn(SchemaMappingUnsortedIndex, typeof (int)); dataTable.Columns.Add(column); } int count = dataTable.Rows.Count; for (int index = 0; index < count; ++index) { dataTable.Rows[index][column] = index; } var schemaTable = new DbSchemaTable(dataTable, returnProviderSpecificTypes); DataRow[] dataRowArray = dataTable.Select(null, "ColumnOrdinal ASC", DataViewRowState.CurrentRows); var dbSchemaRowArray = new DbSchemaRow[dataRowArray.Length]; for (int index = 0; index < dataRowArray.Length; ++index) { dbSchemaRowArray[index] = new DbSchemaRow(schemaTable, dataRowArray[index]); } return dbSchemaRowArray; }
/// <summary> /// 创建树 /// </summary> /// <param name="sqlstring">查询字符串</param> public void BuildTree(DataTable dt,string textName,string valueName) { string SelectedType = "0"; TypeID.SelectedValue = SelectedType; this.Controls.Add(TypeID); //DataTable dt = DbHelper.ExecuteDataset(CommandType.Text, sqlstring).Tables[0]; TypeID.Items.Clear(); //加载树 TypeID.Items.Add(new ListItem("请选择 ", "0")); DataRow[] drs = dt.Select(this.ParentID + "=0"); foreach (DataRow r in drs) { TypeID.Items.Add(new ListItem(r[textName].ToString(),r[valueName].ToString())); string blank = HttpUtility.HtmlDecode(" "); BindNode(r[valueName].ToString(), dt, blank,textName,valueName); } TypeID.DataBind(); }
private static DataTable Diff(DataTable source, DataTable target) { DataTable results = new DataTable(); results.Columns.Add("ElementName", typeof(string)); results.Columns.Add("ColumnName", typeof(string)); results.Columns.Add("Kentico value", typeof(string)); results.Columns.Add("Source value", typeof(string)); foreach (DataRow sourceRow in source.Rows) { foreach (DataColumn col in source.Columns) { var targetRow = target.Select("ElementGUID = '" + sourceRow["ElementGUID"] + "'").FirstOrDefault(); if (targetRow == null) { results.Rows.Add(sourceRow["ElementName"], sourceRow["ElementGUID"], "Element is missing."); } else { string originalValue = sourceRow[col.ColumnName].ToString().Replace("\n", "").Replace("\r", "").Replace("\t", ""); string targetValue = targetRow[col.ColumnName].ToString().Replace("\n", "").Replace("\r", "").Replace("\t", ""); if (!String.Equals(originalValue, targetValue, StringComparison.InvariantCultureIgnoreCase)) { results.Rows.Add(sourceRow["ElementName"], col.ColumnName, originalValue, targetValue); } } } } return results; }
private DataTable LoadTemplateFileDT() { #region 装入模板文件 DataTable templateFileList = new DataTable("templatefilelist"); templateFileList.Columns.Add("fullfilename", Type.GetType("System.String")); templateFileList.Columns.Add("filename", Type.GetType("System.String")); templateFileList.Columns.Add("id", Type.GetType("System.Int32")); templateFileList.Columns.Add("extension", Type.GetType("System.String")); templateFileList.Columns.Add("parentid", Type.GetType("System.String")); templateFileList.Columns.Add("filepath", Type.GetType("System.String")); templateFileList.Columns.Add("filedescription", Type.GetType("System.String")); string path = DNTRequest.GetString("path"); //先以默认模板目录创建文件列表 CreateTemplateFileList(templateFileList, "default", false); if (path.ToLower() != "defalut") { CreateTemplateFileList(templateFileList, path, true); } foreach (DataRow dr in templateFileList.Rows) { foreach (DataRow childdr in templateFileList.Select("filename like '" + dr["filename"] + "_%%'")) { if (dr["filename"].ToString() != childdr["filename"].ToString()) { childdr["parentid"] = dr["id"].ToString(); } } } return templateFileList; #endregion }
/*Metodos que se utilizan para guardar*/ protected void Aceptar(object sender, EventArgs e) { table = (System.Data.DataTable)(Session["Tabla"]); DataRow[] currentRows = table.Select(null, null, DataViewRowState.CurrentRows); string sql = "", texto = ""; if (Ingreso.Visible) { if (string.IsNullOrEmpty(TBnomlinea.Text) == true || currentRows.Length < 1) { Linfo.ForeColor = System.Drawing.Color.Red; Linfo.Text = "Los campos son obligatorios"; } else { sql = "insert into LIN_INVESTIGACION (LINV_CODIGO,LINV_NOMBRE,PROG_CODIGO) VALUES(linvid.nextval, '" + TBnomlinea.Text.ToLower() + "', '" + DDLprog.Items[DDLprog.SelectedIndex].Value.ToString() + "')"; texto = "Datos guardados satisfactoriamente"; Ejecutar(texto, sql); foreach (DataRow row in currentRows) { sql = "insert into TEMA (TEM_CODIGO,TEM_NOMBRE,LINV_CODIGO) VALUES(temaid.nextval, '" + row["TEMAS"] + "', linvid.currval)"; texto = "Datos guardados satisfactoriamente"; Ejecutar(texto, sql); } Quitar(); } } }
protected void WizardSection_ConfirmButtonClick(object sender, EventArgs e) { DataTable dtTest = new DataTable(); if (WizardSection.ActiveStep == this.WizardStep2) { strSQL = "select b.APTestID,b.Sectionid from AP_SavedTest a "; strSQL += " join AP_SavedSection b on a.APTestID = b.APTestID "; strSQL += " and PortfolioID = " + strPID + " and SchoolID = " + SchoolID + " and IsActiveStatus = 1 "; dtTest = CCLib.Common.DataAccess.GetDataTable(strSQL); DataRow[] drs = dtTest.Select("SectionID=1"); if (dtTest.Rows.Count == 0) { strSQL = "insert into AP_SavedTest(PortfolioID,SchoolID,GradeNumber) values(" + strPID + "," + SchoolID + "," + dtStudent.Rows[0]["GradeNumber"].ToString() + ")"; int intAPTestID = CCLib.Common.DataAccess.ExecuteDbWithIntResult(strSQL + "; select @@identity;"); strTestID = intAPTestID.ToString(); } else strTestID = dtTest.Rows[0]["APTestID"].ToString(); if (drs.Length == 0) { try { strSQL = "insert into AP_SavedSection(SectionID,APTestID,APRegID,StartTime,EndTime,Answers) values(1," + strTestID + ",0,'" + lblDate.Text + " 12:00:00 PM','" + DateTime.Now + "','" + ViewState["Result"].ToString() + "')"; CCLib.Common.DataAccess.ExecuteNonQuery(strSQL); } catch (System.Data.SqlClient.SqlException ex)//avoid duplicate records { if (ex.Message.IndexOf("Violation of UNIQUE KEY constraint 'un_section'. ") < 0) throw; } if (dtTest.Rows.Count == 5) { strSQL = "select SectionID,Answers from AP_SavedSection where APTestID=" + strTestID + " order by SectionID"; dtAnswers = CCLib.Common.DataAccess.GetDataTable(strSQL); if (dtAnswers.Rows.Count > 0) { for (int i = 0; i < dtAnswers.Rows.Count; i++) { strAnswers[i] = dtAnswers.Rows[i]["Answers"].ToString(); } scoTest = new CareerCruisingWeb.CCLib.AbilityProfiler.Score(); scoTest.ScoreTest(strAnswers); strSQL = ""; for (int j = 0; j < 6; j++) { strSQL += "update AP_SavedSection set CorrectAnswers = " + scoTest.CorrectAnswers[j].ToString() + ", ConvertedScore = " + scoTest.ScaledScores[scoTest.SubTestMatchingAbilityNameIndex[j]].ToString() + ", Percentile = " + scoTest.PercentileScores[j].ToString() + " where APTestID=" + strTestID + " and SectionID = " + Convert.ToString(j + 1) + "; "; } CCLib.Common.DataAccess.ExecuteNonQuery(strSQL); } DataRow drwPCSCriteria = CareerCruisingWeb.CCLib.PCS.SDPCS.GetPCSCriteria(dtStudent.Rows[0]["GradeNumber"].ToString()); DataRow drwPCSStatus = CareerCruisingWeb.CCLib.PCS.SDPCS.GetPCSStatus(strPID, drwPCSCriteria); CCLib.PCS.SDPCS.UpdatePCSStatusFromSection("AbilityProfiler", strPID, drwPCSCriteria, drwPCSStatus); } strURL = "APSpecialResult.aspx?PP=1&PID=" + strPID; Response.Write("<script language='javascript'>alert('Your changes have been saved.');location.href='" + strURL + "';</script>"); } else Response.Write("<script language='javascript'>alert('There is already an instance of the Ability Profiler associated with your account.');</script>"); } }
public void AddNodeToTree(RadTreeNode parentNode, DataTable _dtTree,string FeildValue, string FeildText, string FeildParent) { try { DataRow[] _Row = null; int k = 0; RadTreeNode currentNode = default(RadTreeNode); _Row = _dtTree.Select(FeildParent + " = " + parentNode.Value.ToString() ,FeildValue + " ASC"); if (_Row.Length > 0) { for (k = 0; k <= _Row.Length - 1; k++) { //If _Row(k)("Ten_Hien_Thi").ToString <> "Phân quyền người dùng" Then RadTreeNode Node = new RadTreeNode(_Row[k][FeildText].ToString(), _Row[k][FeildValue].ToString()); parentNode.Nodes.Add(Node); currentNode = Node; currentNode.Checked = false; AddNodeToTree(currentNode, _dtTree, FeildValue, FeildText, FeildParent); //End If } } //nd _Row(k)("Ten_Hien_Thi").ToString <> "Danh mục tuyến thu" And _Row(k)("Ten_Hien_Thi").ToString <> "Kiểm tra và chốt số liệu" And _Row(k)("Ten_Hien_Thi").ToString <> "Danh mục cụm địa chỉ" } catch (Exception ex) { } }
/// <summary> /// Add value to multi column table, insert rows as needed /// </summary> /// <param name="rval"></param> /// <param name="x"></param> /// <param name="y"></param> private static void AddToMultiColumnTable(DataTable rval, double x, double y) { x = System.Math.Round(x, 2);// example 32.63 var TruncateToTenth = System.Math.Truncate(x * 10.0) / 10.0; var hundrethColumn = x - System.Math.Truncate(x * 10.0) / 10; if (hundrethColumn < 0) hundrethColumn = System.Math.Abs(hundrethColumn); var rows = rval.Select(rval.Columns[0].ColumnName + " = '" + TruncateToTenth.ToString("F2") + "'"); DataRow row ; if (rows.Length == 0) { row = rval.NewRow(); row[0] = TruncateToTenth.ToString("F2"); rval.Rows.Add(row); } else { row = rows[0]; } var colName = hundrethColumn.ToString("F2"); row[colName] = y; }
/// <summary> /// 绑定部门 /// </summary> private void BindTreeView() { DataSet ds = mDpt.GetList(" "); DataTable dt = new DataTable(); dt = ds.Tables[0]; DataRow[] drs = dt.Select(" Dpt_ParentId = 0"); //选出所有根节点 this.tvDaiLi.Nodes.Clear(); TreeNode RootNode = new TreeNode(); RootNode.Text = "<a href='SystemConfigMain.aspx?DPTId=0' onclick='aClick(this);' target='center' >组织机构</a>"; RootNode.Value = "0"; this.tvDaiLi.Nodes.Add(RootNode); foreach (DataRow dr in drs) { string DPTId = dr["Dpt_Id"].ToString(); string DPTName = dr["Dpt_Name"].ToString(); string DPTPARENTID = dr["Dpt_ParentId"].ToString(); TreeNode RootNode2 = new TreeNode(); RootNode2.Text = "<a href='SystemConfigMain.aspx?DPTId=" + DPTId + "' onclick='aClick(this);' target='center' >" + DPTName + "</a>"; RootNode2.Value = DPTId; RootNode.ChildNodes.Add(RootNode2); string SonParentID = DPTId; CreateNode(SonParentID, RootNode2, dt); } //this.tvDaiLi.CollapseAll(); }
/// <summary> /// 输出超纲词表 /// </summary> /// <param name="oldDt">原各等级词汇表</param> /// <param name="maxIndex">选择的最高等级</param> /// <returns>超纲词汇表</returns> public static DataTable NewDataTable(DataTable oldDt, int maxIndex) { DataTable newDt = new DataTable(); //DataRow[] dr = oldDT.Select(); foreach (DataRow row in oldDt.Rows) { //string strName = row["词汇"].ToString(); //取对应字段信息 //string str1 = row["基本"].ToString(); //string str2 = row["较高"].ToString(); //string str3 = row["更高"].ToString(); //string wordfreq = row["词频"].ToString(); if (int.Parse(row[1].ToString()) > maxIndex && int.Parse(row[1].ToString()) <= 0) { newDt.Rows.Add(row); } } //string sql = string.Empty; //for (int i = 1; i <=maxIndex; i++) //{ //} DataRow[] rows = oldDt.Select("[level]>0 and [level]<=" + maxIndex); DataTable dt2 = oldDt.Copy(); //我印象中有Clone方法可以直接复制架构和数据结构但不复制数据的,不要用copy方法。 dt2.Rows.Clear(); foreach (DataRow row2 in rows) { object[] row3 = row2.ItemArray; dt2.Rows.Add(row3); } return(newDt); }