Formatting datetime object - asp.net

I have a dateTime field that i am showing in GridView. The problem is I just need to Show The date of the system And not the time but it shows both date and time. What appropriate formatting should be applied?
this sets the date in textbox:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBoxdate.Text = DateTime.Today.ToShortDateString();
}
}
Retrieves from table:
public static List<Workassign> GetTable()
{
List<Workassign> listValues = new List<Workassign>();
string connectionString = "server=(local);database=project_zeshan;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from Assign_Work", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Workassign ob = new Workassign();
ob.listItem_1 =rdr["listitem_1"].ToString() ;
ob.listItem_2 = rdr["listitem_2"].ToString();
ob.Description = rdr["Description"].ToString();
ob.Date= DateTime.Parse(rdr["Date"].ToString());
ob.Image = rdr["Image"].ToString();
listValues.Add(ob);
}
return listValues;
}
And the gridView.aspx code:
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="listitem_1" HeaderText="ListItem1" />
<asp:BoundField DataField="listItem_2" HeaderText="listItem2" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height= "50px" Width = "100px" ImageUrl='<%# Bind("Image") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</div>
</form>

Try this:
<asp:BoundField DataField="Date" HeaderText="Date" DataFormatString="{0:MM/dd/yyyy}" />

You can format the DateTime however you like using ToString() with format string created from the choices here: MSDN - Custom Date and Time Format Strings
// For a standard U.S.-style date:
myDateTime.ToString("MM/dd/yyyy")
// For ISO-style:
myDateTime.ToString("yyyy-MM-dd")
And so on.
EDIT
#JohnH correctly pointed out that in the specific context of working with a GridView, you wouldn't use ToString or other methods, but rather provide a DataFormatString attribute. I'll leave my answer for general use cases of formatting a date and the link to the MSDN resource containing the available format strings.

Related

Gridview, dynamic data within asp.net not working?

When I use the code below, my gridview (ID=Gridview2) object will populate perfectly using the datasource that is hard coded. I'd like to use a dynamically generated datatable (which when debugging the datatable is populated successfully complete with rows and columns). When I try to bind the dynamic data to my other gridview object (ID=Gridview1) and I verify that it has the datasource as my newly created datatable, nothing appears on the screen?
What am I doing wrong? Do I need to define templates for the dynamic code to work?
<asp:GridView ID="GridView2" runat="server" AllowSorting="True" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowEditButton="True" />
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
<asp:GridView ID="GridView1" runat="server" AutoGenerateEditButton="true"
EmptyDataText="No results found" BackColor="#DEBA84" BorderColor="#DEBA84"
BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"
AllowSorting="True" AutoGenerateColumns="True">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
Code-behind:
protected void btnSearch_Click(object sender, EventArgs e)
{
string domainToQueryFor = "domain";
string pinToQueryFor = "account";
DBConnectionlib.DBClass dbReader = new DBConnectionlib.DBClass();
dbReader.connectionInformation = #"Server=tcp:XXXXXXXXX,1433 ;Database=" + databaseName + ";Trusted_Connection=false;UID=" + databaseUserName + ";Pwd=" + databasePassword + "; ApplicationIntent=ReadWrite;Timeout=60;MultiSubnetFailover=True";
dbReader.tableName = tableName;
string currentSqlQuery = "select * from " + dbReader.tableName + " WHERE domain like '" + domainToQueryFor + "' and pin like '" + pinToQueryFor + "'";
dbReader.queryStatement = currentSqlQuery;
List<string> results = dbReader.readFromSqlDatabaseReturnList();
DataTable dt = createDataTable(results);
GridView1.DataSource = dt;
GridView1.DataBind();
}
I had to add this to get it to portray dynamically
foreach (System.Data.DataColumn item in dt.Columns)
{
BoundField nameColumn = new BoundField();
nameColumn.DataField = item.ColumnName;
nameColumn.HeaderText = item.ColumnName;
GridView1.Columns.Add(nameColumn);
}
Basically without the column names explicitly stated/added, the gridview will not display. They could probably also be hard coded in the html code with a <%bind%> command, but I wanted it more dynamic so I did it the above way.

Remove Empty row in gridview which is added automatically at the bottom of gridview

I am using grid view to show records from database. Gridview has pagination and pagesize is set as 15. And one column has link field when user click this link it proceed some functionality. Now what is my problem is
1) when number of records less than page size the last page is
shrunk. it's k for me. but on clicking view link in grid view the
empty row added automatically. how do i remove these empty row?
2) on clicking view link the page index changed to 1. example i am in
3 page of grid view and clicking view link in 3rd page the page index
number changed to 1 but the page shows 3rd row record. how do i fix
this..?
please any can help me.. thanks in advance
grid view code:-
<asp:GridView ID="gvGRNListAll" runat="server" AutoGenerateColumns="False" Style="width: 100%;"
AllowPaging="True" PageSize="15" OnPageIndexChanging="gvGRNListAll_PageIndexChanging"
CellPadding="4" ForeColor="#333333" BorderColor="#CCCCCC" ShowHeaderWhenEmpty="True"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<PagerStyle CssClass="pager" />
<Columns>
<asp:TemplateField HeaderText="S.No">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" Width="10%" />
</asp:TemplateField>
<asp:BoundField DataField="LocationName" HeaderText="Location" />
<asp:BoundField DataField="SupplierName" HeaderText="Supplier Name" />
<asp:BoundField DataField="GRNNo" HeaderText="GRN No" />
<asp:BoundField DataField="InvoiceNo" HeaderText="In.No">
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="GRNDate" HeaderText="GRNDate" />
<asp:TemplateField HeaderText="Action" SortExpression="ExId" ControlStyle-ForeColor="Blue">
<ItemTemplate>
<asp:HiddenField ID="hdnStoreCode" runat="server" Value='<%# Eval("StoreCode") %>' />
<asp:HiddenField ID="hdnGRNNo" runat="server" Value='<%# Eval("GRNNo") %>' />
<asp:LinkButton ID="lbView" OnClick="lbView_Click" runat="server" Text="View"></asp:LinkButton>
</ItemTemplate>
<ControlStyle ForeColor="#FF3300" />
<HeaderStyle CssClass="GridHeaderROW" Width="10%" />
<ItemStyle CssClass="GridItemROW" Width="10%" />
</asp:TemplateField>
</Columns>
<EmptyDataRowStyle HorizontalAlign="Center" VerticalAlign="Bottom" ForeColor="#FF3300" />
<EmptyDataTemplate>
No Records Found.
</EmptyDataTemplate>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
On PageIndexChanged
protected void gvGRNListAll_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvGRNListAll.PageIndex = e.NewPageIndex;
SearchData();
gvGRNListAll.PageIndex = 0;
}
Searchdata Code :
public void SearchData()
{
DataTable dtGRN = objBAL.FilterGRNScannedList("filterGRNScannedList", suppliercode, grnno, locationcode, Fromdate, Todate, "");
gvGRNListAll.DataSource = dtGRN;
gvGRNListAll.DataBind();
}
Onclick event Code :
if (sender is LinkButton)
{
GridViewRow gvrCurrent = ((LinkButton)sender).NamingContainer as GridViewRow;
hdnGRNNo = (HiddenField)gvrCurrent.FindControl("hdnGRNNo");
hdnStore = (HiddenField)gvrCurrent.FindControl("hdnStoreCode");
gvGRNListAll.Rows[gvrCurrent.RowIndex].BackColor = System.Drawing.Color.Empty;
gvGRNListAll.Rows[gvrCurrent.RowIndex].BackColor = System.Drawing.ColorTranslator.FromHtml("#D8D8D8");
if (hdnGRNNo != null && hdnStore != null)
{
GetGRNListForNo(hdnGRNNo.Value, Convert.ToInt32(hdnStore.Value));
}
}
on RowDataBound do something like below
private void gvGRNListAll_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[6].Text == "") // here add the cell no at which the row is coming blank.
e.Row.Visible = false;
}
Hope it helps

Hide Gridview column when null

I have a gridview in the front end showing 4-5 columns. Need to hide one of the column when the values are NULL.
<asp:GridView ID="gvProducts" runat="server" BackColor="#DEBA84"
BorderColor="#DEBA84"
BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" AutoGenerateColumns="False" AllowPaging="True" PageSize="100" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="CategoryId" SortExpression="CategoryId" HeaderText="CategoryId" Visible="false" />
<asp:BoundField DataField="MerchantName" HeaderText="MerchantName" SortExpression="MerchantName" />
<asp:BoundField DataField="StoreName" HeaderText="StoreName" SortExpression="StoreName" />
<asp:BoundField DataField="StoreAddress" HeaderText="StoreAddress" SortExpression="StoreAddress" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True"
ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True"
ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
If I want to hide StoreName column from code-behind. How to achieve that ?
You can Use RowDataBound Event of GridView
protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string val = e.Row.Cells[0].ToString(); //check first cell value
if(string.IsNullorEmpty(val) )
{
gvSearchEngine.Columns[0].Visible = false; //Hides First Column
}
}
}
Yes, you can dynamically create the boundfield values
from code behind based on your requirment
follow this link
add boundField to gridview in codebehind file C#
try e.Row.Cells[0].Controls[0].Visible = false;

fixing width of a gridview in asp.net

I want to fix width of gridview. I am filling gridview as following;
sorgu = "select urun.urunId as \"İş No\",urun.modelNo as \"Model No\",modelAd as \"Model Adı\",bedenAd as \"Beden\", adet as \"Adet\""
+ ",aciklama as \"Açıklama\", kesmeTalimat as \"Kesim Talimatı\", atolyeTalimat as \"Atölye Talimatı\", yikamaTalimat as \"Yıkama Talimatı\", utuTalimat as \"Ütü Talimatı\", (k4.ad+' '+k4.soyad) as \"Kesim\", (k1.ad+' '+k1.soyad) as \"Atölye\""
+ ",(k2.ad+' '+k2.soyad) as \"Yıkama\",(k3.ad+' '+k3.soyad) as \"Ütü\", (k5.ad+' '+k5.soyad) as \"Kontrol\" from kullanici k1,kullanici k4,kullanici k5,kullanici k2,kullanici k3,model,beden,urun,fason,isTalimat,durum"
+ " where urun.urunId= fason.urunId and urun.urunId=isTalimat.urunId and urun.urunId=durum.urunId and model.modelNo=urun.modelNo and beden.bedenNo=urun.bedenNo and"
+ " fason.atolye=k1.id and fason.yikama=k2.id and fason.kesimci=k4.id and fason.kontrol=k5.id and fason.utu=k3.id";
connection.Open();
command.Connection = connection;
command.CommandText = sorgu;
dr = command.ExecuteReader();
DataTable dtTumISler = new DataTable();
dtTumISler.Load(dr);
dgvTumIsler.DataSource = dtTumISler;
dgvTumIsler.DataBind();
dr.Close();
connection.Close();
dtTumISler.Dispose();
Here dgvTumİsler is my gridview. I have tried the following code to make fixed length. But it does not work;
for (int i = 0; i < dgvTumIsler.Columns.Count; i++)
{
dgvTumIsler.Columns[i].ItemStyle.Width = 100;
}
Here dgvTumİsler.Columns.Count value is 1. So it does not work. Is there a way to solve this problem or is there another way to make a gridview fixed width.
HTML code:
<asp:GridView ID="dgvTumIsler" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" OnSelectedIndexChanged="dgvTumIsler_SelectedIndexChanged">
<Columns>
<asp:CommandField ButtonType="Button" SelectText="Seç" ShowCancelButton="False" ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="false" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
Here is an example how you can do it.Give it a try
<asp:GridView ID="GridView1" AutoGenerateEditButton="True" runat="server" AutoGenerateColumns="False" width="600px">
<Columns>
<asp:BoundField HeaderText="UserId"
DataField="UserId"
SortExpression="UserId" ItemStyle-Width="400px"></asp:BoundField>
</Columns>
</asp:GridView>
You can use the CssClass attribute to set a css class and use that to set the width
<RowStyle CssClass="myRow">
...
<asp:CommandField ButtonType="Button" SelectText="Seç" CssClass="mybutton"/>
...
<style>
.myRow td{width: 100px;}
.mybutton{width: 100px}
</style>

Incorrect syntax near 'int' when using updatecommand on a gridview

I have a problem that when ever I try to update a record in the database using gridview update event handler and an updatecommand in sqldatascource
I get the following exception
Incorrect syntax near 'int'.
the weird thing is when I reload the page I find that the record was updated successfully but yet I need this exception message not to appear what should I do
update event handler
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int BusId = Convert.ToInt32(((DataKey)GridView1.DataKeys[e.RowIndex]).Value);
TextBox Capacity =(TextBox) row.Cells[1].Controls[0];
TextBox DriverName =(TextBox) row.Cells[3].Controls[0];
TextBox Phone =(TextBox) row.Cells[4].Controls[0];
SqlDataSource1.UpdateParameters.Add("capaity", Capacity.Text);
SqlDataSource1.UpdateParameters.Add("id", BusId.ToString());
SqlDataSource1.UpdateParameters.Add("driver", DriverName.Text);
SqlDataSource1.UpdateParameters.Add("phone", Phone.Text);
SqlDataSource1.Update();
}
gridview asp.net code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Bus Number" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" Height="326px" Width="1017px" OnRowUpdating="GridView1_RowUpdating">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="Bus Number" HeaderText="Bus Number" ReadOnly="True" SortExpression="Bus Number" />
<asp:BoundField DataField="Capacity" HeaderText="Capacity" SortExpression="Capacity" />
<asp:BoundField DataField="NumberOfBooking" HeaderText="NumberOfBooking" SortExpression="NumberOfBooking" ReadOnly="True" />
<asp:BoundField DataField="Driver" HeaderText="Driver" SortExpression="Driver" />
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" ShowHeader="False" />
<asp:BoundField DataField="Date Added" HeaderText="Date Added" SortExpression="Date Added" DataFormatString="{0:MM/dd/yyyy}" ReadOnly="True" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
the updatecommand
UpdateCommand="UPDATE Buses SET Capacity = #capaity WHERE VechileId = #id ;UPDATE Vechile SET Driver = #driver, Phone = #phone
WHERE VechileId = #id">

Resources