本文整理汇总了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;
}
示例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;
}
示例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();
}
示例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();
}
}
示例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;
}
示例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;
}
示例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();
}
示例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!!!";
}
}
}
示例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();
}
示例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;
}
示例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;
}
示例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();
}
示例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();
}
}
示例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;
}