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.
Related
I am new in asp.net development
I have created a project its working fine but i want to select the Designation from drop down but want to store the id of the designation instead of the designation
Here is my Asp.net Code for my Project
protected void BindData()
{
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "Select * from EmployeeDetails";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conn.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("ADD"))
{
TextBox txtAddEmpID = (TextBox)GridView1.FooterRow.FindControl("txtAddEmpID");
TextBox txtAddName = (TextBox)GridView1.FooterRow.FindControl("txtAddName");
DropDownList ddlDesignation = (DropDownList)GridView1.FooterRow.FindControl("ddlDesignation");
TextBox txtAddCity = (TextBox)GridView1.FooterRow.FindControl("txtAddCity");
TextBox txtAddCountry = (TextBox)GridView1.FooterRow.FindControl("txtAddCountry");
conn.Open();
string cmdstr = "insert into EmployeeDetails(empid,name,designation,city,country) values(#empid,#name,#designation,#city,#country)";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#empid", txtAddEmpID.Text);
cmd.Parameters.AddWithValue("#name", txtAddName.Text);
cmd.Parameters.AddWithValue("#designation", ddlDesignation.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#city", txtAddCity.Text);
cmd.Parameters.AddWithValue("#country", txtAddCountry.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlDesignation = (DropDownList)e.Row.FindControl("ddlDesignation");
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "Select * from Designation";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
ddlDesignation.DataSource = ds.Tables[0];
ddlDesignation.DataTextField = "designation";
ddlDesignation.DataValueField = "id";
ddlDesignation.DataBind();
ddlDesignation.Items.Insert(0, new ListItem("--Select--", "0"));
this.TextBox1.Text = ddlDesignation.SelectedItem.ToString();
conn.Close();
}
}
and also this is my aspx.cs code for project
<asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="false" ShowFooter="true" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_OnRowDataBound"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Employee ID">
<ItemTemplate>
<asp:Label ID="lblEmpID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "empid") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddEmpID" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddName" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<ItemTemplate>
<asp:Label ID="lblDesignation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "designation") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDesignation" runat="server" >
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "city") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddCity" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "country") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddCountry" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<FooterTemplate>
<asp:LinkButton ID="lbtnAdd" runat="server" CommandName="ADD" Text="Add" Width="100px"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You need to get value from SelectedValue property of dropdwon.
cmd.Parameters.AddWithValue("#designation", ddlDesignation.SelectedValue.ToString());
Did you try
var e = document.getElementById("ddlDesignation");
var strDesigId = e.options[e.selectedIndex].value;
document.getElementById("TextBox1").value = strDesigId;
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
In Grid view I am having one field Items Group. I want to group all the Item group values together in gridview row wise with header name as Itemgroup.
Like Header Text as Itemgroup values followed by its values respectfully.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" HorizontalAlign="Center">
<Columns>
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("TestItemName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Items Group">
<ItemTemplate>
<asp:Label ID="lblGroup" runat="server" Text='<%# Eval("TestItemGroup") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:TextBox ID="txtItemGroup" runat="server" Text='<%# Eval("ItemGroup") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblGroup12" runat="server" Text='<%# Eval("TestItemID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Label ID="lblItemValue" runat="server" Text='<%# Eval("TestItemValues") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Default Values">
<ItemTemplate>
<asp:Label ID="lblDefaultValues" runat="server" Text='<%# Eval("DefaultValues") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Binding Grid view in .cs:
int ID = Convert.ToInt32(txtID.Text);
sqlstr = "select * from Test_Items where TestID = '" + ID + "'";
SqlDataAdapter da = new SqlDataAdapter(sqlstr, con);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
btnSend1.Visible = true;
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "", "alert('Invalid ID (or) No Data to Display..!');", true);
}
For Better understanding Ex:
http://www.pathology-software.com/images/pathology-software/patholgy-screenshot7.jpg
Thank you in Advance
You can inject the needed separator rows by adding “separator records” to the data source before binding it to the GridView.
Here is an example I came across:
protected override void Render(HtmlTextWriter writer)
{
string lastSubCategory = String.Empty;
Table gridTable = (Table)gvProducts.Controls[0];
foreach (GridViewRow gvr in gvProducts.Rows)
{
HiddenField hfSubCategory = gvr.FindControl("hfSubCategory") as
HiddenField;
string currSubCategory = hfSubCategory.Value;
if (lastSubCategory.CompareTo(currSubCategory) != 0)
{
int rowIndex = gridTable.Rows.GetRowIndex(gvr);
// Add new group header row
GridViewRow headerRow = new GridViewRow(rowIndex, rowIndex,
DataControlRowType.DataRow, DataControlRowState.Normal);
TableCell headerCell = new TableCell();
headerCell.ColumnSpan = gvProducts.Columns.Count;
headerCell.Text = string.Format("{0}:{1}", "SubCategory",
currSubCategory);
headerCell.CssClass = "GroupHeaderRowStyle";
// Add header Cell to header Row, and header Row to gridTable
headerRow.Cells.Add(headerCell);
gridTable.Controls.AddAt(rowIndex, headerRow);
// Update lastValue
lastSubCategory = currSubCategory;
}
}
base.Render(writer);
}
FULL ARTICLE
<asp:Literal ID="litDataLoader" runat="server">
</asp:Literal>
<asp:GridView ID="gvTemp" runat="server" AutoGenerateColumns="false" BorderWidth="0" ShowHeader="false" ShowFooter="false">
<Columns>
<asp:TemplateField ControlStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblTestItemName" runat="server" Text='<%#Eval("TestItemName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ControlStyle-Width="220px">
<ItemTemplate>
<asp:Label ID="lblTestItemValues" runat="server" Text='<%#Eval("Itm") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ControlStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblDefaultValues" runat="server" Text='<%#Eval("DefaultValues") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Binding Grid view in .cs:
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
private void bindData()
{
string Query = "select TestItemID,TestItemName,TestItemValues,DefaultValues,TestID,ItemGroup,isnull(TestItemGroup,'-') as TestItemGroup, (ItemGroup + ' ' + TestItemValues) as Itm from Test_Items where TestID = '" + ViewState["id"].ToString() + "'";
SqlDataAdapter da = new SqlDataAdapter(Query, con);
DataTable dt = new DataTable();
da.Fill(dt);
var rows = dt.AsEnumerable().Select(s => new { id = s.Field<string>("TestItemGroup"), }).Distinct().ToList();
int count = rows.Count;
if (dt.Rows.Count > 0)
{
StringBuilder build = new StringBuilder();
foreach (var row in rows)
{
string Name = row.id != "-" ? row.id : " ";
build.Append("<b>" + Name + "</b>");
DataTable dts = new DataTable();
dts = dt.Select("TestItemGroup = '" + row.id + "'").CopyToDataTable();
gvTemp.Visible = true;
gvTemp.DataSource = dts;
gvTemp.DataBind();
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvTemp.RenderControl(hw);
string gridHTML = sw.ToString().Replace("\"", "'").Replace(System.Environment.NewLine, "");
build.Append(gridHTML);
gvTemp.Visible = false;
}
litDataLoader.Text = build.ToString();
}
}
I wanted to load the grid columns vertically with data's coming from database.Please someone help me.I wanted to further edit in the gridcolumn. below is my code
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" Width="95%" style="text-align:center;" GridLines="Both"
AutoGenerateColumns="false" DataKeyNames="WORKSHEET_ID" HeaderStyle-ForeColor="White" onrowediting="EditTaskStatus" onrowupdating="UpdateTaskStatus" onrowcancelingedit="CancelTaskStatus"
AllowPaging ="true" emptydatatext="No Approval Task" OnPageIndexChanging = "OnPaging" BackColor="AliceBlue" Font-Size = "11pt" AlternatingRowStyle-BackColor = "#F2F2F2" RowStyle-BorderWidth="1" AlternatingRowStyle-BorderWidth="1"
HeaderStyle-BackColor = "#00829c" HeaderStyle-BorderColor="#CC9966" PagerStyle-CssClass="pagenation" HeaderStyle-BorderWidth="1px" HeaderStyle-BorderStyle="Solid" EditRowStyle-Wrap="true"
PageSize = "5">
<Columns>
<asp:TemplateField Visible="false" ItemStyle-Width = "30px" HeaderText = "Id">
<ItemTemplate>
<asp:Label ID="lblid" runat="server"
Text='<%# Eval("WORKSHEET_ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "50px" HeaderText ="Total Hours">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server"
Text='<%# Eval("TOTAL_HOURS")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Final Status" ItemStyle-Width = "50px">
<ItemTemplate>
<asp:Label ID="lblFinalStatus" runat="server" Text='<%# Eval("MGR_STATUS") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="ddlTaskStatus">
<asp:ListItem Text="Accept" Value="1"></asp:ListItem>
<asp:ListItem Text="Decline" Value="2"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText ="Comments">
<EditItemTemplate>
<asp:TextBox ID="txtComments" runat="server"
Text='<%# Eval("MGR_COMMENTS") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ItemStyle-Width = "50px">
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" runat="server" CommandName="Edit" ImageUrl="~/images/edit.gif" Width="16" Height="16" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" runat="server" CommandName="Update" ImageUrl="~/images/action_check.gif" Width="16" Height="16" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/images/action_delete.gif" Width="16" Height="16" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Please help me in the backend i have given the code as
protected void BindGridviewData()
{
DataTable dt = new DataTable();
string strQuery = "SELECT * from Master_Worksheets where MGR_CODE ='" + lblUsername.Text + "' AND (MGR_STATUS='New' OR MGR_STATUS='Decline')";
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand(strQuery);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
gvconverted.DataSource = ConvertColumnsAsRows(dt);
gvconverted.DataBind();
gvconverted.HeaderRow.Visible = false;
}
public DataTable ConvertColumnsAsRows(DataTable dt)
{
DataTable dtnew = new DataTable();
//Convert all the rows to columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
dtnew.Columns.Add(Convert.ToString(i));
}
DataRow dr;
// Convert All the Columns to Rows
for (int j = 0; j < dt.Columns.Count; j++)
{
dr = dtnew.NewRow();
dr[0] = dt.Columns[j].ToString();
for (int k = 1; k <= dt.Rows.Count; k++)
dr[k] = dt.Rows[k - 1][j];
dtnew.Rows.Add(dr);
}
return dtnew;
}
I guess you need to swap the rows and columns of Datatable.
If that is what you need then please refer this link. It will help you
http://www.codeproject.com/Articles/44274/Transpose-a-DataTable-using-C
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" />