I have Gridview to show all the data from a datatable.
<asp:GridView ID="GridView1" runat="server"
AllowPaging="True" Width="100%" PageSize="20"
AutoGenerateColumns="true"
CssClass="applicationList-grid" CellPadding="4" ForeColor="#333333" EmptyDataText="No Data!">
</asp:GridView>
and the gridview binded by
string sql = "SELECT * from ApplicationForm";
DataTable dt = GetDataTable(connectionString, sql);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
There is some date fields. The date showing like 04/03/2014 00:00:00 in gridview. I want to format the date with only date no time.
I just try dataformatstring="{MM/dd/yyyy} but it is not working.
You can convert it by below usage-
<span><%# Eval("columnname", "{0:MM/dd/yyyy}")</span>'
Or in SQL
CONVERT( VARCHAR(10), "columnname" ,110)
Note- 110 is the country code.
You can do like this inside your <asp:GridView>
<asp:boundfield datafield="Date_Column" dataformatstring="{0:MMMM d, yyyy}" htmlencode="false" />
Make sure that HtmlEncode is set to False, otherwise it will not work
put :
DataFormatString="{0:MM-dd-yyyy}"
and :
htmlencode="false"
on your bound field tag. You can see the format which you want.
Related
I have a gridview that is getting data from a stored procedure. Column A is a date field. Column B has the text active (for all rows). However, I would like to change the text of 'active' (in the status column) to 'expired' based on the date - so if it's today's date or older, show expired. I know I could execute a job on the SQL server to change the column before importing into my table. However, I would like to only change the text and not alter the DB if possible. So, how would I manipulate the active column to show expired based on today's date.
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
tblMytable.DataSource = dt;
tblMytable.DataBind();
con.Close();
}
The webform:
<asp:GridView ID="tblMytable" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="DateField" HeaderText="Date" />
<asp:BoundField DataField="Status" HeaderText="Status" />
</Columns>
</asp:GridView>
If you make it a TemplateField you have much more control over the data and you can then use a Ternary operator to apply some logic.
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<%# Convert.ToDateTime(Eval("DateField")) < DateTime.Now ? "Expired" : "Active" %>
</ItemTemplate>
</asp:TemplateField>
I'm trying to fill a GridView with a RadioButton and data from a CreditCardList. However, it's doubling the columns for each field... one full set of columns then another complete set (sans the RadioButton) I've checked creditCardList.items.Count and made sure it's just 1 (which it is). What am I doing wrong?
aspx:
<asp:GridView ID="gvCards" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
<Columns>
<asp:TemplateField HeaderText="Sel">
<ItemTemplate>
<asp:RadioButton ID="Sel" runat="server" GroupName="rad" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Customer ID" />
<asp:BoundField DataField="Card ID" HeaderText="Card ID" />
<asp:BoundField DataField="Card Number" HeaderText="Card Number" />
<asp:BoundField DataField="Expiration" HeaderText="Expiration" />
<asp:BoundField DataField="State" HeaderText="State" />
</Columns>
</asp:GridView>
Code behind:
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Customer ID", typeof(string));
dt.Columns.Add("Card ID", typeof(string));
dt.Columns.Add("Card Number", typeof(string));
dt.Columns.Add("Expiration", typeof(string));
dt.Columns.Add("State", typeof(string));
for (var i = 0; i < creditCardList.items.Count; i++)
{
DataRow row1 = dt.NewRow();
row1["Name"] = creditCardList.items[i].first_name + " " + creditCardList.items[i].last_name;
row1["Customer ID"] = creditCardList.items[i].external_customer_id;
row1["Card ID"] = creditCardList.items[i].id;
row1["Card Number"] = creditCardList.items[i].number;
row1["Expiration"] = creditCardList.items[i].expire_month + "/" + creditCardList.items[i].expire_year;
row1["State"] = creditCardList.items[i].state;
dt.Rows.Add(row1);
}
gvCards.DataSource = dt;
gvCards.DataBind();
Output:
Sel Name Card ID Card Number Expiration State Name Customer ID Card ID Card Number Expiration State
Steve Ricketts %40LDN CON CARD-3F3 xxxxxxxxxxx1000 3/2020 ok Steve Ricketts %40LDN CON CARD-3F3 xxxxxxxxxxx1000 3/2020 ok
set AutoGenerateColumns="false" .
<asp:GridView ID="MyGrid" runat="server" AutoGenerateColumns="false">
<Columns>
</Columns>
</asp:GridView>
Remarks
When the AutoGenerateColumns property is set to true, an AutoGeneratedField object is automatically created for each field in the data source. Each field is then displayed as a column in the GridView control in the order that the fields appear in the data source. This option provides a convenient way to display every field in the data source; however, you have limited control of how an automatically generated column field is displayed or behaves.
Instead of letting the GridView control automatically generate the column fields, you can manually define the column fields by setting the AutoGenerateColumns property to false and then creating a custom Columns collection. In addition to bound column fields, you can also display a button column field, a check box column field, a command field, a hyperlink column field, an image field, or a column field based on your own custom-defined template.
i want to display some fields from my database in GridView but my problem is, it show all the field i want in one new field
this is my code
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
and this is c# code
GridView1.DataSource = (from x in db.Products
select x.name + x.phoneNumber + x.proviance + x.description + x.city + x.Address).ToList();
GridView1.DataBind();
how to display some fields of a table (not all fields) into gridView in c# in asp.net
With Respect
So by default GridView generates columns for all fields/columns in the data set it was given. To select what you see you need to turn this off and explicitly declare desired columns:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="name of the column in the data set"
HeaderField="header to show on the UI"/>
... and so on for other columns ...
</Columns>
</asp:GridView>
I have a connected SQL Server database in Visual Studio and am displaying its content in a grid. I created a dropdown menu with the column names as selectable options and a text field to filter for specific content, e.g., DropDown = "Start" - Textfield = 14.03.2015 = Filter Column "Start" for each entry that contains "14.03.2015" - and display it in the Grid.
I'm basically done with that part. The only problem left that I'm facing is whenever I enter a date - e.g., 14.03.2015 it only displays dates which start at 00:00:00 - the other entries that do not start at 00:00:00 are ignored and I can't figure out how to modify this to work properly.
The Grid looks like this: http://abload.de/img/untitled123yqkyn.png
And I am using the following C# code to filter:
protected void Button1_Click(object sender, EventArgs e)
{
string FilterExpression = string.Empty;
if (DropDownList1.SelectedValue.ToString().Equals("Start"))
{
FilterExpression = string.Format("Start = '{0}'", TextBox1.Text);
}
else if (DropDownList1.SelectedValue.ToString().Equals("End"))
{
FilterExpression = string.Format("End = '{0}'", TextBox1.Text);
}
else if (DropDownList1.SelectedValue.ToString().Equals("Creation Time"))
{
FilterExpression = string.Format("DateTimeCreated = '{0}'", TextBox1.Text);
}
else if (DropDownList1.SelectedValue.ToString().Equals("Last Modified"))
{
FilterExpression = string.Format("LastModifiedTime = '{0}'", TextBox1.Text);
}
else
{
FilterExpression = string.Concat(DropDownList1.SelectedValue, " Like '%{0}%'");
}
SqlDataSource1.FilterParameters.Clear();
SqlDataSource1.FilterParameters.Add(new ControlParameter(DropDownList1.SelectedValue, "TextBox1", "Text"));
SqlDataSource1.FilterExpression = FilterExpression;
}
This is my Grid:
Organizer
Room
Creation Time
Start
End
Last Modified
<asp:TextBox ID="TextBox1" runat="server" Width="315px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" Width="100px"/>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Reset Search" Width="100px"/>
<br/>
<br/>
<asp:GridView ID="GridView1" runat="server" BorderColor="#F9F9F9" BorderStyle="Solid" CellPadding="4" ForeColor="#333333" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1" AllowSorting="True" pagesize="1000" AllowPaging="True" HorizontalAlign="Center">
<AlternatingRowStyle BackColor="White"/>
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" ItemStyle-HorizontalAlign="Center"/>
<asp:BoundField DataField="Organizer" HeaderText="Organizer" SortExpression="Organizer" ConvertEmptyStringToNull="False" HtmlEncode="False" HtmlEncodeFormatString="False" InsertVisible="False"/>
<asp:BoundField DataField="Room" HeaderText="Room" SortExpression="Room"/>
<asp:BoundField DataField="DateTimeCreated" HeaderText="Creation Time" SortExpression="DateTimeCreated"/>
<asp:BoundField DataField="Start" HeaderText="Start" SortExpression="Start" />
<asp:BoundField DataField="End" HeaderText="End" SortExpression="End"/>
<asp:BoundField DataField="LastModifiedTime" HeaderText="Last Modified" SortExpression="LastModifiedTime" />
<asp:CheckBoxField DataField="Cancelled" HeaderText="Cancelled" SortExpression="Cancelled" ItemStyle-HorizontalAlign="Center" />
</Columns>
<EditRowStyle BackColor="#2461BF"/>
<FooterStyle BackColor="#E1000F" Font-Bold="True" ForeColor="White"/>
<HeaderStyle BackColor="#E1000F" Font-Bold="True" ForeColor="White" Font-Underline="false"/>
<PagerStyle BackColor="#E1000F" ForeColor="White" HorizontalAlign="Center"/>
<RowStyle BackColor="#F9F9F9"/>
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333"/>
</asp:GridView>
<asp:SqlDataSource ID="xyz" runat="server" ConnectionString="<%$ ConnectionStrings:VCConnectionString %>" SelectCommand="SELECT * FROM [xyz]"></asp:SqlDataSource>
</center>
Please excuse the quality of the code, I'm completely new to C# and for that matter programming in itself. I hope that there is someone able to help me.
What happens if you change all of the filters to use 'LIKE':
if (DropDownList1.SelectedValue.ToString().Equals("Start"))
{
FilterExpression = string.Format("Start LIKE '{0}%'", TextBox1.Text);
}
Then, you're not matching against an exact date (at midnight), but matching any date-times which start with that date.
Update
Or perhaps you could try this...
if (DropDownList1.SelectedValue.ToString().Equals("Start"))
{
FilterExpression = string.Format("Start >= '{0} 0:00:00' AND Start <= '{1} 23:59:59'", TextBox1.Text, TextBox1.Text);
}
Update 2
... Or if you really want to make sure you get all records from that final second of 23:59:59, you could use this (I think)...
if (DropDownList1.SelectedValue.ToString().Equals("Start"))
{
FilterExpression = string.Format("Start >= '{0} 0:00:00' AND Start < DATEADD(day,1,'{1}')", TextBox1.Text, TextBox1.Text);
}
Notice that the version looks for records less than your given date "plus one day".
Personally, I would use the "Update 1" script, and compare the dates against 23:59:59, even though, yes, it would ignore records created in that final second of the day (eg at 23:59:59.403).
The problem is due to the fact you're filtering on a datetime value; if you set only the date part the system interprets it as at midnight. Try to pass also the time value and it will work.
EDIT:
The problem is due the conversion from string and datetime:
else
{
FilterExpression = string.Concat(DropDownList1.SelectedValue, " Like '%{0}%'");
}
Perhaps changing your logic to use the value as a dateime should work.
In the folowing example the first doesn't work, the second one does:
SELECT *
FROM [Events]
WHERE EventDate LIKE '%2012-06-08%'
SELECT *
FROM [Events]
WHERE EventDate >= '2012-06-08' AND EventDate <= '2012-06-08 23:59:59'
I am pulling data from an access database to show in a GridView control on a ASP.NET project. It works fine but I want to see if I can format the data that is being pulled. Currently any currency is being truncated from xx.xx to just the dollar amounts. Also the dates are displaying mm/dd/yyyy hh/mm/ss AM/PM
I tried editing the database itself to the right values (I set the currency field to "Currency" and the date field to "Short Date" but when I pull that date it still shows them not formatted.
EDIT: Sorry, had to take the code down
Any ideas?
Thank you
in the grid view of yours add the property called DataFormatString
DataFormatString examples:
{0:dd MMMM yyyy} - gives 24 February 2006
{0:MMM dd} - gives Feb 24 (substitue MMM with MMMM for the full month name
instead of abbreviation)
{0:dd/MM/yy} - gives 24/02/06
{0:dd/MM/yyyy} - gives 24/02/2006
Sample Code
<asp:BoundField HeaderText="Date"
DataField="SampleDate"
DataFormatString="{0:MM/dd/yyyy}" >
MSDN BoundField.DataFormatString Property
You just need to set the dataformatstring with how you want it to be populated.
As exemplified on the MSDN page:
Money:
<asp:BoundColumn HeaderText="Price" DataField="Price"
DataFormatString="{0:c}" />
With the {0:c}, placing a number after the c value (such as {0:c2}) will give you that many decimal places.
Date:
<asp:boundfield datafield="MyDate" dataformatstring="{0:MM/dd/yyyy}" />
One solution would be:
<asp:GridView ID="gvLEmployees" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("Name") %>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<%# Convert.ToDateTime(Eval("JoinDate")).ToShortDateString() %>
OR
<%# Convert.ToDateTime(Eval("JoinDate")).ToString("d") %>
</ItemTemplate>
</asp:TemplateField>
</Column>
</Gridview>
You have to Create a BoundField, set its properties including the property dataformatstring which you can use to set format of the field appear in the GridView, and add it to the GridView control.
here below some code
public GridView Cr_GridView(string[] ColNames,string[] ColLable, string[] ColFormat)
{
GridView GV = new GridView();
int x = ColNames.GetUpperBound(0);
for (int i = 0; i < x; i++)
{
BoundField GvField = new BoundField();
GvField.DataField = ColNames[i];
GvField.HeaderText = ColLable[i];
GvField.DataFormatString = ColFormat[i];// for example "{0:dd/MM/yyyy}" for a date field
GV.Columns.Add(GvField);
}
return GV;
}
You can also check if you are using Template Field:
<asp:TemplateField HeaderText="last_modified_date">
<ItemTemplate>
<asp:Label ID="lblModyDate" runat="server" Font-Size="10px" CssClass="ControlStyleUpperCase"
Text='<%# Bind("last_modified_date","{0:dd/MM/yyyy HH:mm:tt}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>