1.Search Functionality in DropdownList
When this plugin is added to any ComboBox/ DropDown List, it presents the user with search facility
Steps
- Copy the below code in the ContentPlaceHolderScripts
<%--=====================================================================================--%>
<%--Script for Search Facility in DropDownLists --%>
<link href="../plugins/select/bootstrap-select.css" rel="stylesheet" />
<script src="../plugins/select/bootstrap-select.js"></script>
<script type="text/javascript">
$(document).ready(function () { $(".select2").selectpicker(); });
$(document).ready(function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
$(".select2").selectpicker();
}
});
</script>
- Now Set the following attributes of every DropDownList control you wish to have the search facility
class="form-control select2"
data-live-search="true"
2.Using Time
To store Time(7) Data Type Values from Database to a Variable
TimeSpan StopTime = rdrMain.GetTimeSpan(rdrMain.GetOrdinal("LectureStartTime"));
<td data-label="Out time" style="height: 30px;"><%# DateTime.Parse(Eval("OutTime").ToString()).ToString("hh:mm tt")%> </td>
<td data-label="In Time" style="height: 30px;">
<%# Eval("InTime") != DBNull.Value ? DateTime.Parse(Eval("InTime").ToString()).ToString("hh:mm tt") : "" %></td>
<td data-label="Total Hrs" style="height: 30px;">
<%#(Eval("TotalTime") != DBNull.Value ? DateTime.Parse(Eval("TotalTime").ToString()).ToString("HH:mm"):"")%></td>
To display a Time(7) variable in a textbox with formatting do like this:
TimeSpan duration = rdrMain.GetTimeSpan(rdrMain.GetOrdinal("OutTime"));
DateTime time = DateTime.Today.Add(duration);
txtMovementOutTime.Text = time.ToString("hh:mm tt");
3.Using Currency Symbol & Decimal Places
using System.Globalization;
using System.Threading;
protected void Page_PreInit(object sender, EventArgs e)
{
CultureInfo ci = new CultureInfo("en-IN");
Thread.CurrentThread.CurrentCulture = ci;
base.InitializeCulture();
}
To display Rs Currency with proper commas (For Listview )
<td style="text-align:right;"><%# Eval("Amount","{0:c}")%></td>
To just display the amount properly formatted without Currency Symbol
<td style="text-align:right;"><%# Eval("Amount","{0:N}")%></td>
To display in a TextBox
txtTotalAmount.Text = TotalOutstanding.ToString("N");
To display from a DataReader Field
txtTotalAmount.Text = String.Format("{0:N}", rdrMain["BalanceAmount"]);
4.Date Formates
To format Date in Table
<td data-label="Start Date"><%# Eval("FromDate","{0:dd/MM/yyyy}")%></td>
To get today’s formatted date
txtFromDate.Text = DateTime.Today.ToString("dd/MM/yyyy");
To save Control Values of Date Data Type, Follow the steps:
DateTime dtDOB;
try
{
dtDOB = DateTime.ParseExact(txtDOB.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
catch
{
ShowMessage("Please type DOB in dd/MM/yyyy format!", "Error");
return;
}
Now use the dtDOB variable while saving the values
objcmd.Parameters.Add("@DOB", SqlDbType.Date).Value = dtDOB;
To get Date in DD/MM/YYYY format
SELECT CONVERT(VARCHAR(10), SYSDATETIME(), 103)
5.Using Data Tables
//Declaration of Datatable
DataTable dtTemplate = new DataTable();
//Creation of Fields
dtTemplate.Columns.Add("PostedBy", typeof(string));
//Row Creation
DataRow dr2 = dtTemplate.NewRow();
//Value assigning
dr2["ChatDetails"] = rdrMain["ChatDetails"].ToString();
//Adding Row Back to Datatable
dtTemplate.Rows.Add(dr2);
foreach(DataRow row in dtTable.Rows)
{
TextBox1.Text = row["ImagePath"].ToString();
}
DataTable dtTable = new DataTable();
dtTable.Clear();
dtTable.Columns.Add("Name");
dtTable.Columns.Add("Marks");
DataRow drRow = dtTable.NewRow();
drRow["Name"] = "ravi";
drRow["Marks"] = "500";
dt.Rows.Add(drRow);
To Add Column at a specific Location
DataColumn dcCol = dtTable.Columns.Add("SrNo");
dcCol.SetOrdinal(0);
To Add Columns with Data Type
dtTable.Columns.Add("NoticeTo", typeof(string));
dtTable.Columns.Add("Description", typeof(string));
To Remove
dtTable.Columns.Remove("StudentEnrollID");
dtTable.Columns.Remove("StudentID");
dtTable.Columns.Remove("FathersCellNo");
To Iterate
foreach (DataRow row in dtMain.Rows)
{
for (int j = 5; j < dtList.Columns.Count - 6; j++)
{
TotalLectures = TotalLectures + Convert.ToInt32(drMain[j].ToString() == "" ? "0" : drMain[j].ToString());
}
}
foreach (DataRow row in dtList.Rows)
{
row["SrNo"] = Counter++;
}
To search a single value
DataRow dr = table1.Rows.Find("idcolumnName = value");
DataRow[] dr = table1.Select("idcolumnName = value");
6.Formatting Tables
<table id="myChequeRegister" class="table-hover table-bordered table-responsive table-striped responsiveTable" style="width: 100%">
<thead > Without any Class
7.Formating Numbers
CultureInfo us = new CultureInfo("en-IN");
DecimalNumber.ToString("N",us);
This will display the number properly formatted in Indian Format 12,20,234.75
DecimalNumber.ToString("C",us);
Replacing N with C will result in display of Currency symbol also
To display SQLDataReader fields in above formats, do like this
Convert.ToDecimal(rdr[“Amount”].ToString()).ToString(“C”,us)
8.Creating a Clickable Button in Listview
<table id="myTable"
class="table-hover table-bordered table-responsive table-striped responsiveTable"
style="width: 100%">
<asp:ListView ID="lstRegister" runat="server" DataKeyNames="EntryID" OnItemEditing="lstRegister_ItemEditing">
<LayoutTemplate>
<thead>
<tr>
<th><i style="font-size: 20px" class="fa fa-edit"></i></th>
<th>Event</th>
</tr>
</thead>
<div id="itemplaceholder" runat="server">
</div>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ToolTip="Edit" Style="font-size: 20px"
CssClass="fa fa-edit" runat="server" ID="imgEdit" CommandName="Edit"></asp:LinkButton>
</td>
<td data-label="Event"><%# Eval("EventName")%></td>
</tr>
</ItemTemplate>
</asp:ListView>
</table>
In the code behind,
protected void lstRegister_ItemEditing(object sender, ListViewEditEventArgs e)
{
ListViewItem item = lstRegister.Items[e.NewEditIndex];
hdEntryID.Value = lstRegister.DataKeys[item.DataItemIndex].Values["EntryID"].ToString();
//We can access any value specified in DataKeyNames
DisplayRecord(Convert.ToInt64(hdEntryID.Value));
}
protected void lstRegister_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
hdEntryID.Value = lstRegister.DataKeys[e.ItemIndex].Values["EntryID"].ToString();
DeleteTheRecord();
DisplayRegister();
}
9.How to find out max entry id
INSERT INTO [LIB.CurrentAwareness] (EntryDate,Type,MemberID) OUTPUT INSERTED.EntryID
VALUES(@EntryDate,@Type,@MemberID)
10.Upload zip file and extract in folder
if(FileUpload1.HasFile == true)
{
string extractPath = Server.MapPath("~/CounselingDocument/" + ddlType.SelectedValue + "/" + ddlInstitute.SelectedValue + "/" + ddlForm.SelectedValue + "/");
if (!Directory.Exists(extractPath))
{
//If Directory (Folder) does not exists. Create it.
Directory.CreateDirectory(extractPath);
}
using (ZipFile zip = ZipFile.Read(FileUpload1.PostedFile.InputStream))
{
zip.ExtractAll(extractPath, ExtractExistingFileAction.DoNotOverwrite);
}
11.Bulk Copy In SQL Server Using C#
Bulk copy from a table, view, or the result set of a Transact-SQL statement into a data file where the data is stored in the same format as the table or view. This is called a native-mode data file.
Example: Inset all data from datatable to SQL Database table using bulk copy
DataTable dtStudDetails = new DataTable("dtStudDetails");
using (SqlBulkCopy sqlbulk = new SqlBulkCopy(Con, SqlBulkCopyOptions.Default, Trans))
{
sqlbulk.DestinationTableName = "dbo.StudentCertificateDetails";
sqlbulk.ColumnMappings.Add("EntryID", "EntryID");
sqlbulk.ColumnMappings.Add("Parameter", "Parameter");
sqlbulk.ColumnMappings.Add("Value", "Value");
sqlbulk.WriteToServer(dtStudDetails);
}