CheckBox Not Sending Checked Value to Database C# Asp - c#

I am making a Attendance System in which I get Student Record from student table in a Gridview with a check box. tick the check box for students present and leave unchecked for absent.
After that i submit my record to attendance system.
Problem: If I Check or left unchecked it will show the Absent in Database Results after submission of attendance please check my code.
HTML
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="RecordTablesss.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LabelSr" runat="server" Text=<%#Eval("Sr_Number") %>></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LabelName" runat="server" Text=<%#Eval("Name") %>></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LabelFN" runat="server" Text=<%#Eval("F_Name") %>></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckAttendence" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="ButtonSubmit" runat="server" Text="Submit" OnClick="SaveAttendence" style="width: 61px" />
</div>
</form>
</body>
</html>
Code Behind:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
namespace RecordTablesss
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
loadData();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void loadData()
{
SqlConnection con = new SqlConnection("Data Source=HammadMaqbool;Initial Catalog=FYP_Demo;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("Select Sr_Number,Name,F_Name From Registerd_Student",con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
protected void SaveAttendence(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
string sta = "A";
CheckBox chkVar_ = row.FindControl("CheckAttendence") as CheckBox;
if (chkVar_.Checked)
sta = "P";
string StudentName = (row.FindControl("LabelName") as Label).Text;
string F_Name = (row.FindControl("LabelFN") as Label).Text;
int Number = int.Parse( (row.FindControl("LabelSr") as Label).Text);
//From Here to onword Database Operations. ..
SqlConnection conn = new SqlConnection("Data Source=HammadMaqbool;Initial Catalog=FYP_Demo;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("Insert into Attendance_B values('"+Convert.ToInt32(Number)+"','"+StudentName+"','"+F_Name+"','"+sta+"')",conn);
cmd.ExecuteNonQuery();
}
}
}
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
}
}
}

As You said #Thomas Krojer Answer also not solving your issue but it should do.
The resone you are getting chkVar_.Checked always false.because On Page_Load you are binding gridview again with out checking if it is a postback.
Try this.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
loadData();
}
}
It will solve your problem surely..

I think you do not really write what you mean:
string sta = "";
CheckBox chkVar_ = row.FindControl("CheckAttendence") as CheckBox;
if (chkVar_.Checked)
sta = "P";
sta = "A";
I thin you mean:
string sta = "";
CheckBox chkVar_ = row.FindControl("CheckAttendence") as CheckBox;
if (chkVar_.Checked)
{
sta = "P";
}
else
{
sta = "A";
}
you see the difference?

you just need to correct code
if (chkVar_.Checked)
{
sta = "P";
}
else
{
sta = "A";
}

Related

PageIndexChanging event for GridView not firing

I'm building an ASP.NET web application. I have an .ASPX page where I created a static GridView that I fill (with a SQL Server stored procedure) after the click of a button. I need to implement paging, but it doesn't work: when I click on page 2, 3 or whatever, the GridView seems to disappear.
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="UDC.aspx.cs" Inherits="DynamicStoreWebApplication.UDC" %>
<link href="Controls.css" rel="stylesheet" type="text/css" />
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>DynamicStore Web - Unità di carico</title>
</head>
<body>
<form id="form1" runat="server">
<div runat="server">
<asp:PlaceHolder ID="PlaceHolderHeader" runat="server"></asp:PlaceHolder>
<div style="float: left; width: 10%; background: #fff2e6;">
<asp:PlaceHolder ID="PlaceHolderMenu" runat="server"></asp:PlaceHolder>
</div>
<div style="padding: 25px; padding-left: 200px; width: 90%;">
<asp:Label ID="DateFromLbl" runat="server" Text="Dal giorno: " CssClass="label"></asp:Label>
<asp:TextBox ID="DateFrom" runat="server" Width="130px" TextMode="Date" CssClass="dropdown" Font-Names="Tahoma">2000-01-01</asp:TextBox>
<asp:Label ID="DateToLbl" runat="server" Text="Al giorno: " CssClass="label"></asp:Label>
<asp:TextBox ID="DateTo" runat="server" Width="130px" TextMode="Date" CssClass="dropdown" Font-Names="Tahoma"></asp:TextBox>
<asp:Label ID="Ricerca" runat="server" Text="Ricerca: " CssClass="label"></asp:Label>
<asp:TextBox ID="Search" runat="server" Width="95px" TextMode="SingleLine"></asp:TextBox>
<asp:Label ID="Risultati" runat="server" Text="Ultimi risultati: " CssClass="label"></asp:Label>
<asp:CheckBox ID="TopResults" runat="server" EnableViewState="true" ViewStateMode="Enabled"/>
<asp:Button ID="btnSubmit" runat="server" Text="Visualizza UDC" CssClass="control-button" OnClick="btnSubmit_Click"/>
<br />
<br />
<div style = "overflow-x:auto; width:100%">
<asp:GridView ID="GridView1" runat="server" CssClass="mydatagrid" PagerStyle-CssClass="pager" HeaderStyle-CssClass="header"
RowStyle-CssClass="rows" EnableSortingAndPagingCallbacks="True" AutoGenerateEditButton="False" ShowHeaderWhenEmpty="True"
EnableViewState="true" AllowPaging="True" PageSize="5" OnPageIndexChanging="GridView1_PageIndexChanging">
</asp:GridView>
</div>
</div>
<asp:PlaceHolder ID="PlaceHolderFooter" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
ASPX.CS (code behind)
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
namespace DynamicStoreWebApplication
{
public partial class UDC : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UserControl uc1 = (UserControl)Page.LoadControl("~/Header.ascx");
PlaceHolderHeader.Controls.Add(uc1);
UserControl uc2 = (UserControl)Page.LoadControl("~/Menu.ascx");
PlaceHolderMenu.Controls.Add(uc2);
UserControl uc3 = (UserControl)Page.LoadControl("~/Footer.ascx");
PlaceHolderFooter.Controls.Add(uc3);
DateTo.Text = DateTime.Today.ToString("yyyy-MM-dd");
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
BindGridView();
}
protected void BindGridView()
{
string conn = "";
conn = ConfigurationManager.ConnectionStrings["Connection"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
try
{
objsqlconn.Open();
SqlCommand objcmd = new SqlCommand("DY_FindUdcList", objsqlconn);
objcmd.CommandType = CommandType.StoredProcedure;
SqlParameter RCp = objcmd.Parameters.Add("#RC", SqlDbType.Int);
RCp.Direction = ParameterDirection.ReturnValue;
SqlParameter DateFromp = objcmd.Parameters.Add("#DateFrom", SqlDbType.DateTime);
DateFromp.Value = DateFrom.Text;
SqlParameter DateTop = objcmd.Parameters.Add("#DateTo", SqlDbType.DateTime);
DateTop.Value = DateTo.Text;
SqlParameter UdcCelp = objcmd.Parameters.Add("#UdcCel", SqlDbType.Int);
UdcCelp.Value = -1;
SqlParameter TopResultsp = objcmd.Parameters.Add("#TopResults", SqlDbType.Bit);
if (TopResults.Checked)
{
TopResultsp.Value = 1;
}
else
{
TopResultsp.Value = 0;
}
SqlParameter Searchp = objcmd.Parameters.Add("#Search", SqlDbType.VarChar);
Searchp.Value = Search.Text;
SqlParameter Operp = objcmd.Parameters.Add("#Oper", SqlDbType.VarChar);
Operp.Value = "";
SqlParameter Termp = objcmd.Parameters.Add("#Term", SqlDbType.VarChar);
Termp.Value = "";
SqlParameter Errorep = objcmd.Parameters.Add("#Errore", SqlDbType.VarChar);
Errorep.Value = "";
Errorep.Direction = ParameterDirection.Output;
SqlDataAdapter adapter = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
objcmd.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
finally
{
objsqlconn.Close();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridView();
}
}
}
Your code should work but remove EnableSortingAndPagingCallbacks="True" from the gridview declaration and try it. I think you have not also allowed sorting..

How to achieve bulk save in Gridview using ASP.NET with C#

I have got a Gridview which gets populated with multiple rows as follows where user is allowed to edit Alternate names for the viewed rows after he can bulk save the edited columns.
I tried achieving this using Edit template but I could not achieve this because when the user tries to edit the next row immediately the previous "edited" column contents are erased back to original.
How can I achieve this using gridview
On edit action of the GridView, your change happens only on your browser (client side) until you save the change of current row. You need to save the row and refresh GridView to begin editing the next row.
The typical implementation is to place two button on Edit template - Cancel and Save button to commit the change of the edited row. When clicking on the save button, your postback event will be picked up on server side code (with event argument e that contain which row was on edit and row data that you updated). You save the data to database and refresh the GridView. At that moment, you should be able to see the GridView with updated content. You are ready to click on the Edit button of the next row.
Use this and Edit According to you this is working for me perfectly.
<!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>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("[id$=txtRecievedDate]").datepicker({
showOn: 'button',
buttonImageOnly: true,
dateFormat: "yy-mm-dd",
buttonImage: 'http://jqueryui.com/demos/datepicker/images/calendar.gif'
});
});
</script>
<style type = "text/css">
input[type=text], select{background-color:#FFFFD2; border:1px solid #ccc}
</style>
</head>
<body style = "font-family:Arial;font-size:10pt">
<form id="form1" runat="server">
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"
DataKeyNames = "id" onrowdatabound="gvCustomers_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label1" runat="server" Text="SelectEdit"></asp:Label>
<asp:CheckBox ID = "chkAll" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
<asp:TextBox ID="txtID" runat="server" Text='<%# Eval("id") %>' ReadOnly="true" Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cartridge Set No" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID="lblCartridgeSetNo" runat="server" Text='<%# Eval("CartridgeSetNo") %>'></asp:Label>
<asp:TextBox ID="txtCartridgeSetNo" runat="server" Text='<%# Eval("CartridgeSetNo") %>' ReadOnly="true" Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID = "lblcurrentstatus" runat="server" Text='<%# Eval("currentstatus") %>'></asp:Label>
<asp:Label ID = "lblstatus" runat="server" Text='<%# Eval("status") %>' Visible = "false"></asp:Label>
<asp:DropDownList ID="ddlstatus" runat="server" Visible = "false">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="date Recieved" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("dateRecieved") %>'></asp:Label>
<asp:TextBox ID="txtRecievedDate" runat="server" Text='<%# Eval("dateRecieved") %>' Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comments" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID="lblComments" runat="server" Text='<%# Eval("comments") %>'></asp:Label>
<asp:TextBox ID="txtComments" runat="server" Text='<%# Eval("comments") %>' Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick = "Update" Visible = "false"/>
</form>
</body>
</html>
CS file
using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Linq;
using System.Configuration;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
SqlCommand cmd = new SqlCommand("SELECT [Id],[CartridgeSetNo],[status] ,[dateRecieved],[Comments] ,case when status = 1 then 'Received but not usable' when status = 0 then 'Received and Usable' else 'Not Received' end as currentstatus FROM DrugAllocate ");
gvCustomers.DataSource = this.ExecuteQuery(cmd, "SELECT");
gvCustomers.DataBind();
}
private DataTable ExecuteQuery(SqlCommand cmd, string action)
{
string conString = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
cmd.Connection = con;
switch (action)
{
case "SELECT":
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
case "UPDATE":
con.Open();
cmd.ExecuteNonQuery();
con.Close();
break;
}
return null;
}
}
protected void Update(object sender, EventArgs e)
{
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
if (isChecked)
{
SqlCommand cmd = new SqlCommand("UPDATE DrugReceipt SET Comments=#Comments, dateRecieved=#dateRecieved , status = #status where Id = #Id");
cmd.Parameters.AddWithValue("#Comments", row.Cells[5].Controls.OfType<TextBox>().FirstOrDefault().Text);
string status = row.Cells[3].Controls.OfType<DropDownList>().FirstOrDefault().SelectedItem.Value;
if (status == "Received and Usable")
{
status="0";
}
if (status == "Received but not usable")
{
string comments=row.Cells[5].Controls.OfType<TextBox>().FirstOrDefault().Text;
status = "1";
if (comments == "")
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('comment is mendatry');", true);
break;
}
}
if (status == "Not Received")
{
status = "2";
}
cmd.Parameters.AddWithValue("#status", status);
cmd.Parameters.AddWithValue("#dateRecieved", row.Cells[4].Controls.OfType<TextBox>().FirstOrDefault().Text);
cmd.Parameters.AddWithValue("#Id", gvCustomers.DataKeys[row.RowIndex].Value);
this.ExecuteQuery(cmd, "UPDATE");
}
}
}
btnUpdate.Visible = false;
this.BindGrid();
}
public DataSet GetYesNoValue(string ColumnName)
{
DataTable dtVal = new DataTable();
DataColumn column;
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = ColumnName;
dtVal.Columns.Add(column);
DataSet dsVal = new DataSet();
dtVal.Rows.Add("Received and Usable");
dtVal.Rows.Add("Received but not usable");
dtVal.Rows.Add("Not Received");
dsVal.Tables.Add(dtVal);
return dsVal;
}
protected void OnCheckedChanged(object sender, EventArgs e)
{
bool isUpdateVisible = false;
CheckBox chk = (sender as CheckBox);
if (chk.ID == "chkAll")
{
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked = chk.Checked;
}
}
}
CheckBox chkAll = (gvCustomers.HeaderRow.FindControl("chkAll") as CheckBox);
chkAll.Checked = true;
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
for (int i = 1; i < row.Cells.Count; i++)
{
row.Cells[i].Controls.OfType<Label>().FirstOrDefault().Visible = !isChecked;
if (row.Cells[i].Controls.OfType<TextBox>().ToList().Count > 0)
{
row.Cells[i].Controls.OfType<TextBox>().FirstOrDefault().Visible = isChecked;
}
if (row.Cells[i].Controls.OfType<DropDownList>().ToList().Count > 0)
{
row.Cells[i].Controls.OfType<DropDownList>().FirstOrDefault().Visible = isChecked;
}
if (isChecked && !isUpdateVisible)
{
isUpdateVisible = true;
}
if (!isChecked )
{
chkAll.Checked = false;
}
}
}
}
btnUpdate.Visible = isUpdateVisible;
}
protected void gvCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlCommand cmd = new SqlCommand("SELECT status, case when status = 1 then 'Received but not usable' when status = 0 then 'Received and Usable' else 'Not Received' end as statuscurrent FROM DrugAllocate");
DropDownList ddlstatus = (e.Row.FindControl("ddlstatus") as DropDownList);
ddlstatus.DataSource = this.ExecuteQuery(cmd, "SELECT");
string country = (e.Row.FindControl("lblstatus") as Label).Text;
DataSet ds = new DataSet();
ds = GetYesNoValue("suppStatus");
DataTable dt = new DataTable();
dt = ds.Tables[0];
ddlstatus.DataSource = dt;
ddlstatus.DataTextField = "suppStatus";
ddlstatus.DataValueField = "suppStatus";
ddlstatus.DataBind();
try
{
ddlstatus.Items.FindByValue(country).Selected = true;
}
catch { }
}
}
}

Date Format to a GridView populated with SQL in ASP.net - NOT boundfield

This is the code that creates the GridView everything else is happening with C#, I mean that is populated with the C# code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="STANDBY_JOURNALS Email.aspx.cs" Inherits="STANDBY_JOURNALS_Email.STANDBY_JOURNALS_Email" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="SQL" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="SEND" OnClick="Button2_Click" />
<br />
<asp:GridView ID="GridView1" runat="server" Font-Size="Smaller">
</asp:GridView>
</div>
</form>
</body>
</html>
I need to add Date format to this GridView, but if I try to use BOUNDFIELD, what it does, it creates a column at the beginning of the table, like this:
<asp:GridView ID="GridView1" runat="server" Font-Size="Smaller">
<Columns>
<asp:BoundField DataField="Journal Date" DataFormatString="{0:MMMM d, yyyy}" />
</Columns>
</asp:GridView>
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace STANDBY_JOURNALS_Email
{
public partial class STANDBY_JOURNALS_Email : System.Web.UI.Page
{
SqlConnection vid = new SqlConnection("Data Source=xxxxxxxx; Initial Catalog=xxxxxxxxxxx; User id=xxxxxx; Password=xxxxxxx");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string sqlquery1 = "SELECT * FROM DBO.STANDBY_JOURNALS_DQMS WHERE [Ledger Grp] IN ('ACTUALS','GRP_FXRATE','CONSEGRP') AND [Source] = 'CON' OR [Source] LIKE 'Q%' ORDER BY [Source], [SystemDateTime],[SystemTime] ASC";
String str = sqlquery1;
SqlCommand xp = new SqlCommand(str, vid);
vid.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
GridView1.DataSource = ds;
GridView1.DataBind();
vid.Close();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void Button2_Click(object sender, EventArgs e)
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
String EmailFrom = "xxxxxx#xxxxx.co.nz";
String EmailTo = "xxxxxx#xxxxx.co.nz";
String EmailSubject = "this is a subject";
//String EmailBody = "Cuerpo del Mensaje";
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
MailMessage mm = new MailMessage(EmailFrom, EmailTo);
mm.Subject = EmailSubject;
mm.Body = "Report:<hr />" + sw.ToString(); ;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "XXXXXXXXXXXXXX";
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Port = 25;
smtp.Timeout = 20000;
smtp.Send(mm);
}
}
}
}
}
Anyone can help in how to affect the columns in the table created with the GridView?
Set AutoGenerateColumns property of GridView to false (I think this is the only solution you looking for) and add BoundFields for all required columns.
Or if you are using TemplateFields then there are options to set date format for your TemplateField. No need to add BoundField like:
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "date"
SortExpression="date" >
<ItemTemplate>
<asp:Label ID="lblreceived_at" runat="server"
Text='<%# Eval("date","{0:d}")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
For all options refer:
http://www.codedigest.com/Articles/ASPNET/137_How_to_format_DateTime_in_GridView_BoundColumn_and_TemplateColumn.aspx
In BoudField, Try this format:
DataFormatString="{0:dd/MM/yyyy}"
Output:
01/06/2017 00:00:00
If you add the following Convert function in your SQL query, your purpose will be achieved. For example:
Select CONVERT(varchar,YOUR_DATE_COLUMN,107) as JournalDate, * From YOUR_TABLE_NAME
The easiest way is to just use SQL MID() in the query,
SELECT MID(Journal_Date,1,8) AS JD FROM DBO.STANDBY_JOURNALS_DQMS
It will give you
01/06/17

Error when paging in GridView

I have a GridView with two columns. The first shows a date and the second, the year of the date in the first column. So far everything works well but when I change page, the web fails with the message: "Object reference not set to an instance of an object."
This is my code:
Test.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="qq_site_Test" %>
<!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>TEST</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="5"
AllowSorting="True" AutoGenerateColumns="False"
EnableModelValidation="True" onrowcreated="GridView1_RowCreated"
onpageindexchanged="GridView1_PageIndexChanged"
onpageindexchanging="GridView1_PageIndexChanging">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="creationDate" HeaderText="creationDate" SortExpression="creationDate" />
<asp:TemplateField HeaderText="Year">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Test.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Odbc;
using System.Data;
public partial class qq_site_Test : System.Web.UI.Page
{
static DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
String connectionString = "DSN=kitchenmaster.es.qq-site;";
String sqlQuery = "SELECT * FROM tblSystems WHERE ID < 100";
ds = new DataSet();
OdbcConnection connection = new OdbcConnection(connectionString);
OdbcCommand command = new OdbcCommand(sqlQuery, connection);
OdbcDataAdapter adapter = new OdbcDataAdapter(command);
try
{
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (System.Exception ex)
{
Response.Write(ex.Message);
}
finally
{
if (connection.State == ConnectionState.Open)
connection.Close();
}
}
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
try
{
DateTime dt = (DateTime)DataBinder.Eval(e.Row.DataItem, "creationDate");
e.Row.Cells[GetColumnByID("Year")].Text = dt.Year.ToString();
}
catch (System.Exception ex)
{
Response.Write(ex.Message);
}
}
}
protected int GetColumnByID(String columnName)
{
foreach (DataControlField column in GridView1.Columns)
{
if (column.HeaderText == columnName)
return GridView1.Columns.IndexOf(column);
}
return -1;
}
protected void GridView1_PageIndexChanged(object sender, EventArgs e)
{
GridView1.SelectedIndex = -1;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
if (e.NewPageIndex != -1)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
catch (System.Exception ex)
{
Response.Write(ex.Message);
}
}
}
Can you help me?
This line of code
GridView1.DataSource = ds;
is probably where you are getting the error.
When the GridView1_PageIndexChanging event is called, you have not yet set the value for ds. The only part in your code that does so is in the Page_Load event, and only when it's not a postback.
If I check the value of the e.Row.DataItem in the event GridView1_RowCreated(), the error not occurs but I don't know if it's the right thing to do. The new version of the event is:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
try
{
if (e.Row.DataItem != null)
{
DateTime dt = (DateTime)DataBinder.Eval(e.Row.DataItem, "creationDate");
e.Row.Cells[GetColumnByID("Year")].Text = dt.Year.ToString();
}
}
catch (System.Exception ex)
{
Response.Write("** " + ex.Message);
}
}
}
Please check your "ds" object inside in PageIndexChanging event.
First fill the data set and bind.

multiply the gridview columns

I will post you my code and i will explain what i want to do
<div>
<div>
<asp:GridView ID="gridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
<asp:HiddenField ID="hdValue" runat="server" Value='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Button ID="btnMove" runat="server" Text="Add To Cart" OnClick="btnMove_Click" />
</div>
<div>
<asp:GridView ID="gridView2" runat="server">
<Columns>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="tbQty" runat="server" Width="25px"
MaxLength="3" />
</ItemTemplate>
<ItemStyle Width="25px" HorizontalAlign="Center"/>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<br />
<asp:Button ID="Button1" runat="server" Text="Find the total" />
<asp:Label ID="Label7" runat="server" Text="Total"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<br />
<br />
</div>
and the theo.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class theo : System.Web.UI.Page
{
const string key = "MyDataSource5";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
private void BindGridView()
{
if (Session[key] == null)
{
gridView1.DataSource = GetDataSource();
gridView1.DataBind();
}
else
{
gridView1.DataSource = (DataTable)Session[key];
gridView1.DataBind();
}
}
protected DataTable GetDataSource()
{
try
{
DataTable dt = new DataTable();
dt = new DataTable();
dt.Columns.Add("ID", typeof(int)).AutoIncrement = true;
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Price(Grouch)/Hectares", typeof(float));
DataColumn[] keys = new DataColumn[2];
keys[0] = dt.Columns["ID"];
dt.PrimaryKey = keys;
dt.Rows.Add("1", "Seaside Location", 1.5);
dt.Rows.Add("2", "Arable Land", 0.1);
dt.Rows.Add("3", "Foothills of the mountains", 1.5);
dt.Rows.Add("4", "Industrial Land", 0.1);
dt.Rows.Add("5", "Rolling Farmland", 0.5);
Session[key] = dt;
return dt;
}
catch
{
return null;
}
}
protected void btnMove_Click(object sender, EventArgs e)
{
try
{
DataTable dtMain = Session[key] as DataTable;
//copy the schema of source table
DataTable dtClone = dtMain.Clone();
foreach (GridViewRow gv in gridView1.Rows)
{
CheckBox chk = gv.FindControl("chkSelect") as CheckBox;
HiddenField hdValue = gv.FindControl("hdValue") as HiddenField;
if (chk.Checked)
{
//get only the rows you want
DataRow[] results = dtMain.Select("ID=" + hdValue.Value + "");
//populate new destination table
foreach (DataRow dr in results)
{
dtClone.ImportRow(dr);
}
}
gridView2.DataSource = dtClone;
gridView2.DataBind();
}
}
catch
{
BindGridView();
}
}
}
In this code when i check for example 2 choices from gridview 1 and click the button add to cart then these 2 choices are moving to the second gridview. As you see,I have a textbox for the quantity. I would like when i give the quantity to multiply it with the price.With the button 'find the total' i want to give me the result in the text box.How can i do that?
one simple solution may be useful to you.
protected void Button1_Click(object sender, EventArgs e)
{
int itemCount;
decimal itemPrice, itemTotal;
itemTotal = 0;
itemCount = 0;
itemPrice = 0;
foreach(GridViewRow gridView2Row in gridView2.Rows)
{
TextBox tbCount = gridView2Row.Cells[0].Controls[1] as TextBox;
itemCount = Convert.ToInt32(tbCount.Text);
itemPrice = Convert.ToDecimal(gridView2Row.Cells[3].Text);
itemTotal = itemTotal + (itemCount * itemPrice);
}
TextBox1.Text = itemTotal.ToString();
}

Categories

Resources