I try to bind my list of objects to my datasource.
But as I switched from autogeneratecolums to boundfields, the whole grid is not displayed anymore.
Is there something I miss to let this work proper?
asp:
<asp:GridView ID="grid_article"
AutoGenerateColumns="false"
runat="server"
GridLines="None"
AllowPaging="true"
CssClass="mGrid"
PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt"
OnPageIndexChanging="ArticleGrid_PageIndexChanging">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="cbSelect" runat="server" ReadOnly="false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="itemNumber" HeaderText="Product Number" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="name" HeaderText="Product Name" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="description" HeaderText="Product Description" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="purchasePrice" HeaderText="Purchase Price" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="salesPrice" HeaderText="Sales Price" ReadOnly="true"></asp:BoundField>
</Columns>
</asp:GridView>
code behind:
if (articles != null)
{
if (articles.Count != 0)
{
DataTable dt = new DataTable();
dt.Columns.Add("itemNumber");
dt.Columns.Add("name");
dt.Columns.Add("description");
dt.Columns.Add("purchasePrice");
dt.Columns.Add("salesPrice");
foreach (AccessoryDTO item in articles)
{
DataRow dr = dt.NewRow();
dr["itemNumber"] = item.itemNumber;
dr["name"] = item.name;
dr["description"] = item.description;
dr["purchasePrice"] = item.purchasePrice + " " + item.currency;
dr["salesPrice"] = item.salesPrice + " " + item.currency;
dt.Rows.Add(dr);
}
grid_article.DataSource = dt;
show_record_count(articles.Count);
grid_article.DataBind();
}
else
{
grid_article.DataSource = null;
grid_article.DataBind();
}
}
try like this code that i worked with in sharepoint 2013 :
<asp:GridView ID="OffresGrid" CssClass="dataTable" runat="server" AutoGenerateColumns="false" EmptyDataText="Pas de données." AllowPaging="True" PageSize="1000" OnPageIndexChanging="OffresGrid_PageIndexChanging" OnRowDataBound="OffresGrid_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="Secteur">
<ItemTemplate>
<asp:Label ID="Secteur" runat="server" Text='<%#Eval("Secteur") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Réference">
<ItemTemplate>
<asp:LinkButton ID="Reference" runat="server" Text='<%#Eval("Reference") %>' OnCommand="reference_Command" CommandArgument='<%#Eval("Reference") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Titre">
<ItemTemplate>
<asp:Label ID="Title" runat="server" Text='<%#Eval("Title")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date limité">
<ItemTemplate>
<asp:Label ID="DateLimite" runat="server" Text='<%#Eval("DateLimite")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date de publication">
<ItemTemplate>
<asp:Label ID="DatePublication" runat="server" Text='<%#Eval("DatePublication")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lieux">
<ItemTemplate>
<asp:Label ID="Lieux" runat="server" Text='<%#Eval("Lieux")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
C# code :
DataTable dt = new DataTable();
string Secteur, Reference, Title, DateLimite, DatePublication, Lieux;
dt.Columns.Add("Secteur", typeof(string));
dt.Columns.Add("Reference", typeof(string));
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("DateLimite", typeof(string));
dt.Columns.Add("DatePublication", typeof(string));
dt.Columns.Add("Lieux", typeof(string));
try
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Offres"];
SPListItemCollection coll = list.Items;
foreach (SPListItem item in coll)
{
if (item["Secteur"] != null)
{
Secteur = item["Secteur"].ToString();
}
else
{
Secteur = "";
}
if (item["Reference"] != null)
Reference = item["Reference"].ToString();
else
Reference = " ";
if (item["Title"] != null)
Title = item["Title"].ToString();
else
Title = " ";
if (item["DateLimite"] != null)
DateLimite = item["DateLimite"].ToString();
else
DateLimite = " ";
if (item["DatePublication"] != null)
DatePublication = item["DatePublication"].ToString();
else
DatePublication = " ";
if (item["Lieux"] != null)
Lieux = item["Lieux"].ToString();
else
Lieux = " ";
dt.Rows.Add(Secteur, Reference, Title, DateLimite,
DatePublication, Lieux);
}
OffresGrid.DataSource = dt;
OffresGrid.DataBind();
}
}
}
catch (Exception )
{
}
im trying to insert into table date in this type dd/mm/yyyy.
in the mysql i set the data type to DATE.
when i click add and insert the date this error is shown.
"mysql.data.types.mysqlconversionexpection {"Unable to convert MySQL date/time value to System.DateTime"}"
i cant find the mistake.
thanks alot!!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MySql.Data.MySqlClient;
namespace WebApplication1
{
public partial class usageDisp : System.Web.UI.Page
{
string connectionstring = #"Data Source=localhost; Database=globaldotdb; user ID=root; Password=peleg1708";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//check
BindData();
}
}
private void BindData()
{
using (MySqlConnection cn = new MySqlConnection(connectionstring))
{
MySqlDataAdapter adp = new MySqlDataAdapter(("SELECT tblusage.codeUsage,tblcustom.Customer, tblvendor.Vendor, tblusage.dateStart, tblusage.dateEnd, tblregion.Region, tblservice.Service, tblservice.unit, tblusage.isSecure,tblusage.Usages FROM ((((tblvendor INNER JOIN tblusage ON tblvendor.codeVendor = tblusage.codeVendor) INNER JOIN tblservice ON tblusage.codeService = tblservice.codeService) INNER JOIN tblregion ON tblusage.codeRegion = tblregion.codeRegion) INNER JOIN tblcustom ON tblusage.codeCust = tblcustom.codeCust)"), cn);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
gv.DataSource = dt;
gv.DataBind();
}
}
}
protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int codeusage = int.Parse(gv.DataKeys[e.RowIndex].Value.ToString());
deleteusage(codeusage);
BindData();
}
private void deleteusage(int codeusage)
{
using (MySqlConnection cn = new MySqlConnection(connectionstring))
{
string query = "DELETE FROM tblusage WHERE codeUsage=" + codeusage + " ";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
}
}
protected void gv_DataBound(object sender, EventArgs e)
{
DropDownList DDLCu = gv.FooterRow.FindControl("DDLCu") as DropDownList;
DropDownList DDLVe = gv.FooterRow.FindControl("DDLVe") as DropDownList;
DropDownList DDLSe = gv.FooterRow.FindControl("DDLSe") as DropDownList;
DropDownList DDLRe = gv.FooterRow.FindControl("DDLRe") as DropDownList;
using (MySqlConnection cn = new MySqlConnection(connectionstring))
{
MySqlDataAdapter Cadp = new MySqlDataAdapter(("SELECT * from tblcustom"), cn);
DataTable Cdt = new DataTable();
Cadp.Fill(Cdt);
if (Cdt.Rows.Count > 0)
{
DDLCu.DataSource = Cdt;
DDLCu.DataTextField = "Customer";
DDLCu.DataValueField = "codeCust";
DDLCu.DataBind();
}
MySqlDataAdapter Vadp = new MySqlDataAdapter(("SELECT * from tblvendor"), cn);
DataTable Vdt = new DataTable();
Vadp.Fill(Vdt);
if (Vdt.Rows.Count > 0)
{
DDLVe.DataSource = Vdt;
DDLVe.DataTextField = "Vendor";
DDLVe.DataValueField = "codeVendor";
DDLVe.DataBind();
}
MySqlDataAdapter Sadp = new MySqlDataAdapter(("SELECT * from tblservice"), cn);
DataTable Sdt = new DataTable();
Sadp.Fill(Sdt);
if (Sdt.Rows.Count > 0)
{
DDLSe.DataSource = Sdt;
DDLSe.DataTextField = "Service";
DDLSe.DataValueField = "codeService";
DDLSe.DataBind();
}
MySqlDataAdapter Radp = new MySqlDataAdapter(("SELECT * from tblregion"), cn);
DataTable Rdt = new DataTable();
Radp.Fill(Rdt);
if (Rdt.Rows.Count > 0)
{
DDLRe.DataSource = Rdt;
DDLRe.DataTextField = "Region";
DDLRe.DataValueField = "codeRegion";
DDLRe.DataBind();
}
}
}
protected void lnkAdd_Click(object sender, EventArgs e)
{
DropDownList DDLCu = gv.FooterRow.FindControl("DDLCu") as DropDownList;
DropDownList DDLVe = gv.FooterRow.FindControl("DDLVe") as DropDownList;
DropDownList DDLSe = gv.FooterRow.FindControl("DDLSe") as DropDownList;
DropDownList DDLRe = gv.FooterRow.FindControl("DDLRe") as DropDownList;
DropDownList DDLIS = gv.FooterRow.FindControl("DDLIS") as DropDownList;
TextBox txtds = (TextBox)gv.FooterRow.FindControl("TBDS");
TextBox txtde = (TextBox)gv.FooterRow.FindControl("TBDE");
TextBox txtus = (TextBox)gv.FooterRow.FindControl("TextBoxUnit");
int usage = int.Parse(txtus.Text);
int cc = int.Parse(DDLCu.SelectedValue);
int cv = int.Parse(DDLVe.SelectedValue);
int cs = int.Parse(DDLSe.SelectedValue);
int cr = int.Parse(DDLRe.SelectedValue);
int iss = int.Parse(DDLIS.SelectedValue);
string DS = txtds.Text;
string DE = txtde.Text;
add(cc, cv, cs, cr, usage, iss, DE, DS);
BindData();
Response.Redirect("http://localhost:56717/usageDisp.aspx");
}
private void add(int cc, int cv, int cs, int cr,int usag,int isecure, string ds, string de)
{
using (MySqlConnection cn = new MySqlConnection(connectionstring))
{
string query = "insert into tblusage(codeCust,codeVendor,codeService,codeRegion,Usages,isSecure,dateStart,dateEnd) values (" + cc + "," + cv + "," + cs + "," + cr + "," + usag + "," + isecure + "," + ds + "," + de + ") ";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
}
}
protected void CalendarStart_SelectionChanged(object sender, EventArgs e)
{
TextBox txtds = (TextBox)gv.FooterRow.FindControl("TBDS");
Calendar cas = gv.FooterRow.FindControl("CalendarStart") as Calendar;
txtds.Text = cas.SelectedDate.ToString("d");
}
protected void CalendarEnd_SelectionChanged(object sender, EventArgs e)
{
TextBox txtde = (TextBox)gv.FooterRow.FindControl("TBDE");
Calendar cas = gv.FooterRow.FindControl("CalendarEnd") as Calendar;
txtde.Text = cas.SelectedDate.ToString("d");
}
}
}
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="usageDisp.aspx.cs" Inherits="WebApplication1.usageDisp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="usageDisp" runat="server">
<asp:GridView ID="gv" runat="server"
DataKeyNames="codeUsage"
onrowdeleting="gv_RowDeleting"
AutoGenerateColumns="False" ondatabound="gv_DataBound" ShowFooter="True">
<Columns>
<asp:TemplateField HeaderText="codeusage" Visible="False">
<EditItemTemplate>
<asp:TextBox ID="txtcode" runat="server" Text='<%# Eval("codeUsage") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("codeUsage") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer">
<EditItemTemplate>
<asp:TextBox ID="TXTCust" runat="server" Text='<%# Eval("Customer") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDLCu" runat="server" AutoPostBack="True">
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Customer") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Vendor">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Vendor") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDLVe" runat="server" AutoPostBack="True">
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Vendor") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="dateStart">
<EditItemTemplate>
<asp:TextBox ID="TXTDS" runat="server" Text='<%# Eval("dateStart") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Calendar ID="CalendarStart" runat="server" BackColor="#FFFFCC"
BorderColor="#FFCC66" BorderWidth="1px" DayNameFormat="Shortest"
Font-Names="Verdana" Font-Size="8pt" ForeColor="#663399" Height="108px"
ShowGridLines="True" Width="132px"
onselectionchanged="CalendarStart_SelectionChanged">
<DayHeaderStyle BackColor="#FFCC66" Font-Bold="True" Height="1px" />
<NextPrevStyle Font-Size="9pt" ForeColor="#FFFFCC" />
<OtherMonthDayStyle ForeColor="#CC9966" />
<SelectedDayStyle BackColor="#CCCCFF" Font-Bold="True" />
<SelectorStyle BackColor="#FFCC66" />
<TitleStyle BackColor="#990000" Font-Bold="True" Font-Size="9pt"
ForeColor="#FFFFCC" />
<TodayDayStyle BackColor="#FFCC66" ForeColor="White" />
</asp:Calendar>
<asp:TextBox ID="TBDS" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("dateStart") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="dateEnd">
<EditItemTemplate>
<asp:TextBox ID="TXTDE" runat="server" Text='<%# Eval("dateEnd") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Calendar ID="CalendarEnd" runat="server" BackColor="White"
BorderColor="#3366CC" BorderWidth="1px" CellPadding="1"
DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt"
ForeColor="#003399" Height="108px" Width="132px"
onselectionchanged="CalendarEnd_SelectionChanged">
<DayHeaderStyle BackColor="#99CCCC" ForeColor="#336666" Height="1px" />
<NextPrevStyle Font-Size="8pt" ForeColor="#CCCCFF" />
<OtherMonthDayStyle ForeColor="#999999" />
<SelectedDayStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SelectorStyle BackColor="#99CCCC" ForeColor="#336666" />
<TitleStyle BackColor="#003399" BorderColor="#3366CC" BorderWidth="1px"
Font-Bold="True" Font-Size="10pt" ForeColor="#CCCCFF" Height="25px" />
<TodayDayStyle BackColor="#99CCCC" ForeColor="White" />
<WeekendDayStyle BackColor="#CCCCFF" />
</asp:Calendar>
<asp:TextBox ID="TBDE" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Eval("dateEnd") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="service">
<EditItemTemplate>
<asp:TextBox ID="TXTSe" runat="server" Text='<%# Eval("Service") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDLSe" runat="server" AutoPostBack="True">
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Eval("Service") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="region">
<EditItemTemplate>
<asp:TextBox ID="TXTRe" runat="server" Text='<%# Eval("Region") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDLRe" runat="server" AutoPostBack="True">
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# Eval("Region") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="isSecure">
<EditItemTemplate>
<asp:TextBox ID="TXTIS" runat="server" Text='<%# Eval("isSecure") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDLIS" runat="server">
<asp:ListItem Value="1">true</asp:ListItem>
<asp:ListItem Value="0">false</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label8" runat="server" Text='<%# Eval("isSecure") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="unit">
<EditItemTemplate>
<asp:TextBox ID="TXTunit" runat="server" Text='<%# Eval("unit") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Eval("unit") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="usage">
<EditItemTemplate>
<asp:TextBox ID="TXTusage" runat="server" Text='<%# Eval("Usages") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBoxUnit" runat="server"></asp:TextBox>
<asp:LinkButton ID="lnkAdd" runat="server" onclick="lnkAdd_Click">add</asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label10" runat="server" Text='<%# Eval("Usages") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Operation" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<div>
</div>
</form>
</body>
</html>
you just need to add Convert.ToDateTime() , then your query'll definately work.
but, your doing it in a wrong way.
use Parameterized Query,
A parameterized query is a query in which placeholders are used for
parameters and the parameter values are supplied at execution time.
The most important reason to use parameterized queries is to avoid SQL
injection attacks
In your case, you need to change the insert query:
string query = "insert into tblusage(codeCust,codeVendor,codeService,codeRegion,Usages,isSecure,dateStart,dateEnd) values (" + cc + "," + cv + "," + cs + "," + cr + "," + usag + "," + isecure + "," + Convert.ToDateTime(ds) + "," + Convert.ToDateTime(de) + ") ";
Or, You can change the ds and dt variable datatype
CultureInfo provider = CultureInfo.InvariantCulture;
string format="dd/mm/yyyy";//define your datetime format here
DateTime ds=DateTime.ParseExact(textbox1.Text, format, provider);
DateTime de=DateTime.ParseExact(textbox2.Text, format, provider);
and then pass it to the query,like
string query = "insert into tblusage(codeCust,codeVendor,codeService,codeRegion,Usages,isSecure,dateStart,dateEnd) values (" + cc + "," + cv + "," + cs + "," + cr + "," + usag + "," + isecure + "," +ds + "," + de + ") ";
Edit 2:
private void add(int cc, int cv, int cs, int cr,int usag,int isecure, string ds, string de)
{
using (MySqlConnection cn = new MySqlConnection(connectionstring))
{
string query = "insert into tblusage(codeCust,codeVendor,codeService,codeRegion,Usages,isSecure,dateStart,dateEnd) values (#cc,#cv,#cs,#cr,#usag,#isecure,#ds,#de) ";
MySqlCommand cmd = new MySqlCommand(query, cn);
cmd .Parameters.Add("#cc",MySqlDbType.Int).Value=cc;
cmd .Parameters.Add("#cv",MySqlDbType.Int).Value=cv;
cmd .Parameters.Add("#cs",MySqlDbType.Int).Value=cs;
cmd .Parameters.Add("#cr",MySqlDbType.Int).Value=cr;
cmd .Parameters.Add("#usag",MySqlDbType.Int).Value=usag;
cmd .Parameters.Add("#isecure",MySqlDbType.Int).Value=isecure;
cmd .Parameters.Add("#ds",MySqlDbType.Date).Value=ds;
cmd .Parameters.Add("#de",MySqlDbType.Date).Value=de;
cn.Open();
cmd.ExecuteNonQuery();
}
}
Please consider using parametric queries & Convert.toDateTime().
private void add(int cc, int cv, int cs, int cr,int usag,int isecure, string ds, string de)
{
using (MySqlConnection cn = new MySqlConnection(connectionstring))
{
using (var sqlcmd = new SqlCommand())
{
sqlcmd.Connection = cn;
sqlcmd.CommandText = "insert into tblusage(codeCust,codeVendor,codeService,codeRegion,Usages,isSecure,dateStart,dateEnd) values (#codeCust,
#codeVendor, #codeService, #codeRegion, #Usages, #isSecure, #dateStart, #dateEnd)")
sqlcmd.Parameters.AddWithValue("#codeCust", cc);
sqlcmd.Parameters.AddWithValue("#codeVendor", cv);
sqlcmd.Parameters.AddWithValue("#codeService", cs);
sqlcmd.Parameters.AddWithValue("#codeRegion", cr);
sqlcmd.Parameters.AddWithValue("#Usages", usag);
sqlcmd.Parameters.AddWithValue("#isSecure", isecure);
sqlcmd.Parameters.AddWithValue("#dateStart", Convert.ToDateTime(ds));
sqlcmd.Parameters.AddWithValue("#dateEnd", Convert.ToDateTime(de));
cn.open();
sqlcmd.ExecuteNonQuery();
}
}
}
You have to specify date format.
Sample code:
str_to_date(de,"%d/%m/%Y")
str_to_date is mysql function. Kindly refer MySQL documentation.
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Verify at http://sqlfiddle.com/#!9/46d5b/1
I edit and changed the dateentry for the first row from 05/04/2014 to 06/04/2014. After clicking update, it becomes 04/06/2014. My dateEntry column is a date type format and not a datetime format for your information. I want it to be dd/mm/yyyy format.
If I put anything higher than 12 in the date. etc 16. will have error.
Error following #Arshad advice
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
bindResultGridView();
}
//Logout.Visible = false;
string memName = (String)Session["UserName"];
lblUsername.Text = String.Concat("Welcome Guest!");
if (Session["Username"] != null && Session["Username"] != String.Empty)
{
lblUsername.Text = "Welcome, " + memName + "!";
}
}
private void bindResultGridView()
{
String ConStr = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(ConStr);
try
{
String SQL = null;
SQL = "SELECT BlogID, Name, Blogtype, Description, Dateentry FROM [EntryTable]";
SqlCommand cmd = new SqlCommand(SQL, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
grdBlog.DataSource = dt;
grdBlog.DataBind();
reader.Close();
}
finally
{
con.Close();
}
}
protected void grdBlog_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdBlog.EditIndex = -1;
bindResultGridView();
}
protected void grdBlog_RowEditing(object sender, GridViewEditEventArgs e)
{
grdBlog.EditIndex = e.NewEditIndex;
bindResultGridView();
}
protected void grdBlog_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int selectedRow = e.RowIndex; //get selected row
// get product id from data key
int blogid = (int)grdBlog.DataKeys[selectedRow].Value;
// get current grid view row
GridViewRow row = (GridViewRow)grdBlog.Rows[selectedRow];
TextBox name = (TextBox)row.FindControl("txtName");
// find text box for txtPrice
TextBox blogtype = (TextBox)row.FindControl("txtBlogType");
TextBox description = (TextBox)row.FindControl("txtDescription");
TextBox dateentry = (TextBox)row.FindControl("txtDateEntry");
// Remove $ sign
string strName = name.Text;
string strBlogType = blogtype.Text;
string strDescription = description.Text;
string strDateEntry = dateentry.Text;
DateTime datDate;
if (DateTime.TryParseExact(strDateEntry, new string[] { "dd/MM/yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
updateBlogGridviewRecord(blogid, strName, strBlogType, strDescription, datDate.ToString());
}
else
{
}
}
private void updateBlogGridviewRecord(int blogid, string strName, string strBlogType, string strDescription, string strDateEntry)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "UPDATE EntryTable SET [Name]=#Name, [BlogType]=#BlogType, [Description]=#Description, [DateEntry]=#DateEntry WHERE [BlogID]=#BlogID";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("#BlogID", blogid);
cmd.Parameters.AddWithValue("#Name", strName);
cmd.Parameters.AddWithValue("#BlogType", strBlogType);
cmd.Parameters.AddWithValue("#DateEntry", strDateEntry);
cmd.Parameters.AddWithValue("#Description", strDescription);
myConnect.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
lblError.Text = "Record updated!";
}
else
{
lblError.Text = "Update fail";
}
myConnect.Close();
//Cancel Edit Mode
grdBlog.EditIndex = -1;
bindResultGridView();
}
Source code
<asp:GridView ID="grdBlog" runat="server" style=
"margin-left: 0px" Width="695px" Height="147px" AutoGenerateColumns="False"
onrowcancelingedit="grdBlog_RowCancelingEdit" onrowediting="grdBlog_RowEditing"
onrowupdating="grdBlog_RowUpdating" DataKeyNames="BlogID"
onrowdeleting="grdBlog_RowDeleting" AllowPaging="True"
onpageindexchanging="grdBlog_PageIndexChanging" PageSize="5">
<Columns>
<asp:BoundField DataField="BlogID" HeaderText="BlogID"
SortExpression="BlogID" />
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="BlogType">
<EditItemTemplate>
<asp:TextBox ID="txtBlogType" runat="server" Text='<%# Bind("BlogType") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("BlogType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<EditItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DateEntry">
<EditItemTemplate>
<asp:TextBox ID="txtDateEntry" runat="server" Text='<%# Eval("DateEntry", "{0:dd/MM/yyyy}") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("DateEntry", "{0:dd/MM/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="javascript : return confirm('Confirm delete this record?');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Followed #Chirag Adhvaryu This worked for me.
protected void grdBlog_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int selectedRow = e.RowIndex; //get selected row
// get product id from data key
int blogid = (int)grdBlog.DataKeys[selectedRow].Value;
// get current grid view row
GridViewRow row = (GridViewRow)grdBlog.Rows[selectedRow];
TextBox name = (TextBox)row.FindControl("txtName");
// find text box for txtPrice
TextBox blogtype = (TextBox)row.FindControl("txtBlogType");
TextBox description = (TextBox)row.FindControl("txtDescription");
TextBox dateentry = (TextBox)row.FindControl("txtDateEntry");
// Remove $ sign
string strName = name.Text;
string strBlogType = blogtype.Text;
string strDescription = description.Text;
string strDateEntry = dateentry.Text;
DateTime datDate;
if (DateTime.TryParseExact(strDateEntry, new string[] { "dd/MM/yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
updateBlogGridviewRecord(blogid, strName, strBlogType, strDescription, datDate);
}
else
{
}
}
private void updateBlogGridviewRecord(int blogid, string strName, string strBlogType, string strDescription, DateTime datDate)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "UPDATE EntryTable SET [Name]=#Name, [BlogType]=#BlogType, [Description]=#Description, [DateEntry]=#DateEntry WHERE [BlogID]=#BlogID";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("#BlogID", blogid);
cmd.Parameters.AddWithValue("#Name", strName);
cmd.Parameters.AddWithValue("#BlogType", strBlogType);
cmd.Parameters.AddWithValue("#DateEntry", datDate);
cmd.Parameters.AddWithValue("#Description", strDescription);
myConnect.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
lblError.Text = "Record updated!";
}
else
{
lblError.Text = "Update fail";
}
myConnect.Close();
//Cancel Edit Mode
grdBlog.EditIndex = -1;
bindResultGridView();
}
You can try like this.
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblDate" runat="server" Text='<%# Eval("Date", "{0:dd/MM/yyyy}")%>' >
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Update your DateEntry template field with '<%# Eval("DateEntry", "{0:dd/MM/yyyy}") %>' instead of '<%# Bind("DateEntry") %>'
<asp:TemplateField HeaderText="DateEntry">
<EditItemTemplate>
<asp:TextBox ID="txtDateEntry" runat="server" Text='<%# Eval("DateEntry", "{0:dd/MM/yyyy}") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("DateEntry", "{0:dd/MM/yyyy}") %>'></asp:Label>
</ItemTemplate>
Edit
string strDate = dateentry.Text;
DateTime datDate;
if(DateTime.TryParseExact(strDate , new string[] { "dd/MM/yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
// Call your update method with
}
else
{
//Show validation error message
}
You can validate Date Time like this on client side.
<asp:TemplateField HeaderText="date" SortExpression="date">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("date") %>'></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server" BackColor="Red" ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="Invalid Date" MaximumValue="28/12/9999" MinimumValue="28/12/1000" SetFocusOnError="True" Type="Date"></asp:RangeValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDate" runat="server" Text='<%# Eval("date", "{0:dd/MM/yyyy}")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
I Have a GridView in .aspx page that I want to hide columns based on aspx.cs BindData() method. I have tried using below code but not able to hide. I am using Asp.net with C#.
Below is my GridView with columns and I have also included the Button click code.
<GridView>
<Columns>
<asp:BoundField DataField="id" HeaderText="Id" SortExpression="id"
Visible="false" />
<asp:TemplateField HeaderText="RollNo" >
<ItemTemplate>
<%# Eval("st_rollno")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbsturollno" runat="Server"
Text='<%# Eval("st_rollno") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("st_name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbstuname" runat="Server"
Text='<%# Eval("st_name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Theory">
<ItemTemplate>
<%# Eval("theory")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtheory" runat="Server"
Text='<%# Eval("theory") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("ttotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtheorytotal" runat="Server"
Text='<%# Eval("ttotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lab" >
<ItemTemplate>
<%# Eval("lab")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tblab" runat="Server"
Text='<%# Eval("lab") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("ltotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tblabtotal" runat="Server"
Text='<%# Eval("ltotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tutorial" >
<ItemTemplate>
<%# Eval("tutorial")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtutorial" runat="Server"
Text='<%# Eval("tutorial") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("tutotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtutorialtotal" runat="Server"
Text='<%# Eval("tutotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</GridView>
private void BindData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
if (stype.Equals("L"))
{
query = "SELECT [id], [st_rollno], [st_name], [lab], [ltotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
GridView1.Columns[3].Visible = false;
GridView1.Columns[4].Visible = false;
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
}
else if (stype.Equals("T"))
{
query = "SELECT [id], [st_rollno], [st_name], [theory], [ttotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
GridView1.Columns[5].Visible = false;
GridView1.Columns[6].Visible = false;
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
}
else if (stype.Equals("T-L"))
{
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
query = "SELECT [id], [st_rollno], [st_name], [theory], [ttotal], [lab], [ltotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
}
else
{
query = "SELECT [id], [st_rollno], [st_name],[theory], [ttotal], [lab], [ltotal], [tutorial], [tutotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = #branch_name) AND ([scode] = #scode) AND ([sem_no] = #sem_no) AND ([sess_no] = #sess_no)) ORDER BY [st_rollno]";
}
com = new SqlCommand(query);
com.Parameters.Add("#branch_name", dept);
com.Parameters.Add("#scode", dpsubject.SelectedItem.Text.ToString());
com.Parameters.Add("#sem_no", Int32.Parse(dpsemno.SelectedItem.Text.ToString()));
com.Parameters.Add("#sess_no",Int32.Parse(dpsessional.SelectedItem.Text.ToString()));
using (SqlDataAdapter sda = new SqlDataAdapter())
{
com.Connection = con;
con.Open();
sda.SelectCommand = com;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
}
}
protected void bsubmit_Click(object sender, EventArgs e)
{
this.BindData();
}
<asp:GridView runat="server" ID="GridView1"
AutoGenerateColumns="False" OnPreRender="GridView_PreRender">
<Columns>
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var users = new List<User>
{
new User {FirstName = "John", LastName = "Doe"},
new User {FirstName = "Marry", LastName = "Newton"},
new User {FirstName = "Joe", LastName = "Black"}
};
GridView1.DataSource = users;
GridView1.DataBind();
}
}
protected void GridView_PreRender(object sender, EventArgs e)
{
foreach (DataControlField column in GridView1.Columns)
if (column.HeaderText == "FirstName")
column.Visible = false;
}
With the GrideView.DataBind() you're calling a PostBack that will undo any changed you've made to the front end. Try doing the work on the columns after the DataBind.