当前位置: 首页>>代码示例>>C#>>正文


C# DataTable类代码示例

本文整理汇总了C#中DataTable的典型用法代码示例。如果您正苦于以下问题:C# DataTable类的具体用法?C# DataTable怎么用?C# DataTable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


DataTable类属于命名空间,在下文中一共展示了DataTable类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: getTotalCount

    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;
    }
开发者ID:FaisalRizwan,项目名称:project,代码行数:27,代码来源:Default.aspx.cs

示例2: getPatient

 /// <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;
 }
开发者ID:oofdui,项目名称:ContactCheckup-MassConvert,代码行数:42,代码来源:clsTempData.cs

示例3: Buscar

    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();
    }
开发者ID:jquirogadesarrollador,项目名称:Varu_Original,代码行数:33,代码来源:incapacidades.aspx.cs

示例4: GridViewFriends_RowCommand

    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();
        }
    }
开发者ID:farhad85,项目名称:Salestan,代码行数:60,代码来源:Requests.aspx.cs

示例5: IntroPageBuilder

    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;
    }
开发者ID:oofdui,项目名称:ChanthaburiHospital.com,代码行数:32,代码来源:clsIntroPage.cs

示例6: grdvwViewAsset_RowCommand

    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;

            }

        }
    }
开发者ID:progressiveinfotech,项目名称:PRO_FY13_40_Helpdesk-Support-and-Customization_TerexBest,代码行数:32,代码来源:ViewAsset.aspx.cs

示例7: listarSucursales

 public DataTable listarSucursales()
 {
     SqlDataAdapter da = new SqlDataAdapter("select * from tb_sucursal", cn.getCn);
     DataTable tb = new DataTable();
     da.Fill(tb);
     return tb;
 }
开发者ID:XxkokoxX,项目名称:Proy-FacilitoOnline,代码行数:7,代码来源:Sucursales.cs

示例8: Fill_User_Header

        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();
        }
开发者ID:gtiachile,项目名称:GesRTS,代码行数:30,代码来源:Respaldo+Cataloga.aspx.cs

示例9: btnLogin_Click

    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!!!";
            }
        }
    }
开发者ID:SriramRamachandran,项目名称:SS,代码行数:34,代码来源:Login.aspx.cs

示例10: Button1_Click

    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();
    }
开发者ID:jescudero,项目名称:MiamiAndMiami,代码行数:33,代码来源:Hotels.aspx.cs

示例11: GetUserDetails

    /// <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 = "Yes";
            }
            else
            {
                ValidUser = "No";
            }
        }
        catch
        {

        }
        finally
        {
            UserBAL = null;
        }

        return UserTable;
    }
开发者ID:kamleshdaxini,项目名称:LocalDevelopment,代码行数:33,代码来源:Login.cs

示例12: GetDataTable

    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;
    }
开发者ID:tagcosta,项目名称:PerForms,代码行数:25,代码来源:Default.aspx.cs

示例13: SelectDistinct

    /// <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();
    }
开发者ID:owxy,项目名称:web,代码行数:40,代码来源:Filter.cs

示例14: bindData

    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();

        }
    }
开发者ID:krishnakant,项目名称:WMS,代码行数:30,代码来源:CulpritDefault.aspx.cs

示例15: ExecuteSelectCommand

    // 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;
    }
开发者ID:altras,项目名称:fmi_projects,代码行数:30,代码来源:GenericDataAccess.cs


注:本文中的DataTable类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。