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..
Related
Here i Got some code i tried lot of method, I just able to display the data into my form by using Select query but Am not able to update it, it updating but it just updating old value not new value i changed in textbox
Here is the form
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Editcar.aspx.cs" MasterPageFile="MasterPage2.master" Inherits ="Editcar" %>
<asp:Content ID="formContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<br />
<br />
<br />
<div class="row container">
<form id="form1" runat="server" class="col-md-10" action="update.aspx" methode="post" >
<asp:Table ID="GridView1" class="nav-justified" runat="server" AutoGenerateColumns="false" Height="628px" Width="763px">
<asp:TableRow>
<asp:TableCell>
<h4> Car name:</h4>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="id" runat="server" name="id" Width="301px" Text='<%# Eval("id") %>' Visible="False" CssClass="form-control"></asp:TextBox>
<asp:TextBox ID="carmake" runat="server" Font-Names="carmake" Width="301px" Text='<%# Eval("car_make") %>' CssClass="form-control"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<h4> Car model:</h4>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="carmodel" runat="server" name="carmodel" Text='<%# Eval("car_model") %>' Width="301px" CssClass="form-control"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<h4> Price: </h4>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="price" name="price" runat="server" Width="301px" CssClass="form-control"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<h4> Discounted Price If: </h4>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="d_price" name="d_price" runat="server" Width="301px" CssClass="form-control"/>
</asp:TableCell></asp:TableRow><asp:TableRow>
<asp:TableCell> <h4>Car image (Type url)</h4></asp:TableCell><asp:TableCell>
<asp:TextBox CssClass="form-control" ID="image" name="image" runat="server" />Just Location
</asp:TableCell></asp:TableRow><asp:TableRow>
<asp:TableCell><h4>Avilability</h4></asp:TableCell><asp:TableCell>
<asp:TextBox CssClass="form-control" ID="avail" name="avail" runat="server" />Just Location
</asp:TableCell></asp:TableRow><asp:TableRow>
<asp:TableCell><h4>Quantity</h4></asp:TableCell><asp:TableCell>
<asp:TextBox CssClass="form-control" ID="quantity" name="quantity" runat="server" />Just Location
</asp:TableCell></asp:TableRow><asp:TableRow>
<asp:TableCell>
<h4>Long description </h4>
</asp:TableCell><asp:TableCell>
<asp:TextBox ID="details" name="details" runat="server" Width="295px" CssClass="form-control" Height="81px" TextMode="MultiLine"></asp:TextBox>
</asp:TableCell></asp:TableRow><asp:TableRow>
<asp:TableCell>
<h4>Year </h4>
</asp:TableCell><asp:TableCell>
<asp:TextBox ID="year" name="year" runat="server" Width="295px" CssClass="form-control" ></asp:TextBox>
</asp:TableCell></asp:TableRow><asp:TableRow>
<asp:TableCell>
<h4>Special Discounted(0 0r 1) </h4>
</asp:TableCell><asp:TableCell>
<asp:TextBox ID="special" name="special" runat="server" Width="295px" CssClass="form-control" ></asp:TextBox>
</asp:TableCell></asp:TableRow></asp:Table><asp:Button ID="button" runat="server" Cssclass="btn btn-primary btn-lg btn-block" Text="Update the car" />
<br />
<br />
</form>
</div>
</asp:Content>
Here is the CS file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;
public partial class Editcar : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
var id = Request.QueryString["id"];
string selectquery = "SELECT * FROM product WHERE id=" + #id;
MySqlCommand cmd = new MySqlCommand(selectquery);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
con.Open();
cmd.ExecuteNonQuery();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
id = dr["id"].ToString();
carmake.Text = dr["car_make"].ToString();
carmodel.Text = dr["car_model"].ToString();
price.Text = dr["unitprice"].ToString();
d_price.Text = dr["discountprice"].ToString();
image.Text = dr["image"].ToString();
quality.Text = dr["quantity"].ToString();
avil.Text = dr["availability"].ToString();
details.Text = dr["details"].ToString();
year.Text = dr["year"].ToString();
special.Text = dr["special"].ToString();
}
}
}
}
Here his the update page 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;
using System.Configuration;
using MySql.Data.MySqlClient;
public partial class AdminGroup_Update: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string constor = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
MySqlConnection conn = new MySqlConnection(constor);
var id = Request.QueryString["id"];
var carmake = Request.QueryString["carmake"];
var carmodel = Request.QueryString["carmodel"];
var price = Request.QueryString["price"];
var d_price = Request.QueryString["d_price"];
var image = Request.QueryString["image"];
var quantity = Request.QueryString["quantity"];
var avail = Request.QueryString["avail"];
var details = Request.QueryString["details"];
var year = Request.QueryString["year"];
var special = Request.QueryString["special"];
string sql = "Update product SET car_make=#carmake ,car_model=#carmodel ,UnitPrice=#price ,Discountprice=#d_price ,image=#image ,Quantity=#quality ,availability=#avil ,details=#details ,year=#year ,special=#special WHERE id= #id";
var cmd = new MySqlCommand(sql, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
var param = new MySqlParameter[10];
param[0] = new MySqlParameter("#carmake", MySqlDbType.VarChar, 100);
param[1] = new MySqlParameter("#carmodel", MySqlDbType.VarChar, 100);
param[2] = new MySqlParameter("#price", MySqlDbType.VarChar, 100);
param[3] = new MySqlParameter("#d_price", MySqlDbType.VarChar, 100); // put zero if no discount
param[4] = new MySqlParameter("#image", MySqlDbType.VarChar, 300);
param[5] = new MySqlParameter("#quantity", MySqlDbType.VarChar, 300);
param[6] = new MySqlParameter("#avail", MySqlDbType.VarChar, 2);
param[7] = new MySqlParameter("#details", MySqlDbType.VarChar, 2000);
param[8] = new MySqlParameter("#year", MySqlDbType.VarChar, 4);
param[9] = new MySqlParameter("#special", MySqlDbType.VarChar, 2);
param[10] = new MySqlParameter("#id", MySqlDbType.VarChar, 2);
param[0].Value = carmake;
param[1].Value = carmodel;
param[2].Value = price;
param[3].Value = d_price;
param[4].Value = image;
param[5].Value = quality;
param[6].Value = avil;
param[7].Value = details;
param[8].Value = year;
param[9].Value = special;
param[10].Value =id;
var ex = cmd.ExecuteNonQuery();
if (ex == 1)
{
Response.Redirect("AdminList.aspx");
}
else
{
Response.Write("Error");
}
conn.Close();
}
}
Your button
<asp:Button ID="button" runat="server"
Cssclass="btn btn-primary btn-lg btn-block"
Text="Update the car" />
needs an OnClick setting and an event handler in your code-behind .cs file to handle it.
Webforms / dot net works differently from some other interactive web page frameworks in that most controls post back to the same page rather than posting to another page. So, you don't need a separate update page, and indeed won't be able to use it in the normal course of event processing.
Here in my code i'm trying to let the user edit the gridview and hence update the database accordingly.The gridview is made on a webform page in aspx which shows the user data in tabular structure.But the problem is here that when i click on edit link of gridview it lets me to edit the data but when i update the gridview row,the associated event of onrowupdating doesn't gets called or fired at all.Even when i written all the code for it but still it's not working.What's the problem in this Please help me with this.Below is my whole code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication5.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Welcome To My First Web Form<br />
<h1> Candidate Registration Form</h1>
<br />
<br />
Applicant's Name:
<asp:TextBox ID="TextBox1" runat="server" CausesValidation="True" EnableViewState="False" ValidateRequestMode="Enabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Please enter Your Name!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Applicant's FName"></asp:Label>
:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2" ErrorMessage="Please enter your Father name!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Gender"></asp:Label>: <asp:RadioButtonList ID="gender" RepeatDirection="Horizontal" runat="server" Width="141px" RepeatLayout="Flow">
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="gender" ErrorMessage="Please Choose your Gender" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="E-mail ID"></asp:Label>
:
<asp:TextBox ID="TextBox3" runat="server" OnTextChanged="TextBox3_TextChanged"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox3" Display="Dynamic" ErrorMessage="E-mail address is required">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox3" Display="Dynamic" ErrorMessage="E-mail addresses must be in the format of name#domain.xyz" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ForeColor="Red">Invalid Format</asp:RegularExpressionValidator>
<br />
<br />
<asp:Label ID="Label4" runat="server" Text="password"></asp:Label>
:
<asp:TextBox ID="TextBox4" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="TextBox4" Display="Dynamic" ErrorMessage="Password is Required!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label5" runat="server" Text="Confirm Password"></asp:Label>
:
<asp:TextBox ID="TextBox5" runat="server" TextMode="Password"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="TextBox5" ErrorMessage="The passwords Didn't Match!" ForeColor="Red" ControlToCompare="TextBox4" Display="Dynamic"></asp:CompareValidator>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
<br />
<asp:GridView ID="GridView1" runat="server"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True"
OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating1">
<%-- <Columns>
<asp:BoundField DataField="Cname" />
<asp:BoundField DataField="Cfname" />
<asp:BoundField DataField="Cmail" />
</Columns>--%>
</asp:GridView>
<br />
<br />
</div>
</form>
</body>
</html>
CS code file for this:-
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 System.Data.SqlClient;
using System.Configuration;
namespace WebApplication5
{
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\admin\documents\visual studio 2013\Projects\WebApplication5\WebApplication5\App_Data\Candidates.mdf;Integrated Security=True");
public static int count = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
gvbind();
//DataTable dt = new DataTable();
//dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Name"), new DataColumn("FatherName"), new DataColumn("E-mail") });
//ViewState["Candidates"] = dt;
//GridView1.DataSource = (DataTable)ViewState["Candidates"];
//GridView1.DataBind();
}
}
protected void gvbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Candidates", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void TextBox3_TextChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
count += 1;
int rowIndex = 0;
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Candidates values('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
//if (count > 1)
//{
// DataTable dtCurrentTable = (DataTable)ViewState["Candidates"];
// DataRow drCurrentRow = null;
// if (dtCurrentTable.Rows.Count > 0) {
// //for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
// //{
// drCurrentRow = dtCurrentTable.NewRow();
// int totalrows = dtCurrentTable.Rows.Count;
// dtCurrentTable.Rows.Add(drCurrentRow);
// dtCurrentTable.Rows[totalrows]["Name"] = TextBox1.Text;
// dtCurrentTable.Rows[totalrows]["FatherName"] = TextBox2.Text;
// dtCurrentTable.Rows[totalrows]["E-mail"] = TextBox3.Text;
// rowIndex++;
// //}
// ViewState["Candidates"] = dtCurrentTable;
// GridView1.DataSource = dtCurrentTable;
// GridView1.DataBind();
// TextBox1.Text = string.Empty;
// TextBox2.Text = string.Empty;
// TextBox3.Text = string.Empty;
// }
//}
//else
//{
// DataTable dt = (DataTable)ViewState["Candidates"];
// dt.Rows.Add(TextBox1.Text.Trim(), TextBox2.Text.Trim(), TextBox3.Text.Trim());
// ViewState["Candidates"] = dt;
// TextBox1.Text = string.Empty;
// TextBox2.Text = string.Empty;
// TextBox3.Text = string.Empty;
// BindGrid();
//}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
//protected void BindGrid()
//{
// //GridView1.DataSource = (DataTable)ViewState["Candidates"];
// //GridView1.DataBind();
//}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
gvbind();
}
protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
string name = GridView1.SelectedRow.Cells[0].Text;
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
TextBox textName = (TextBox)row.Cells[0].Controls[0];
TextBox textFname = (TextBox)row.Cells[1].Controls[0];
TextBox texte = (TextBox)row.Cells[2].Controls[0];
////TextBox textadd = (TextBox)row.FindControl("txtadd");
////TextBox textc = (TextBox)row.FindControl("txtc");
GridView1.EditIndex = -1;
con.Open();
SqlCommand cmd = new SqlCommand("update Candidates set Cname='" + textName.Text + "',Cfname='" + textFname.Text + "',Cmail='" + texte.Text + "'where Cname='" + name + "'", con);
cmd.ExecuteNonQuery();
con.Close();
gvbind();
//GridView1.DataBind();
}
}
}
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";
}
I am making an application about article publication. I have 2 tables
"artikulli"
id int Unchecked
tema varchar(250) Checked
abstrakti text
data_publikimit date
path varchar(350)
keywords varchar(350)
kategoria_id int
departamenti_id int
"kategorite"
id int Unchecked
emertimi varchar(350)
I want to display in a dropdown list all values of field "emertimi" and when the user selects one value to save id of that value in table "artikulli".
I have done the following, but I have the problem with syntax because I am using DATALIST.
public partial class AddArticle : System.Web.UI.Page
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
try
{
if (!IsPostBack)
{
Bind();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
public void Bind()
{
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
protected void datalist2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox txtTema = e.Item.FindControl("txtTema") as TextBox;
TextBox txtAbstrakti = e.Item.FindControl("txtAbstrakti") as TextBox;
TextBox txtData = e.Item.FindControl("txtData") as TextBox;
TextBox txtKeywords = e.Item.FindControl("txtKeywords") as TextBox;
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection conn = new SqlConnection(connection);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "Insert into artikulli(tema,abstrakti,data_publikimit,path,keywords,kategoria_id) values (#tema,#abstrakti,#data,#filename,#keywords,#kategoria)";
command.Parameters.Add(new SqlParameter("#tema", txtTema.Text));
command.Parameters.Add(new SqlParameter("#abstrakti", txtAbstrakti.Text));
command.Parameters.Add(new SqlParameter("#data", txtData.Text));
command.Parameters.Add(new SqlParameter("#keywords", txtKeywords.Text));
command.Parameters.Add(new SqlParameter("#kategoria", drpdKategoria.SelectedValue));
FileUpload FileUploadArtikull = (FileUpload)e.Item.FindControl("FileUploadArtikull");
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise se file qe lejohet eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
//add parameters
command.Parameters.AddWithValue("#filename", filename);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Bind();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni ngarkuar asnje artikull');", true);
}
}
}
AddArtikull.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AddArtikull.aspx.cs" Inherits="AddArticle" MasterPageFile="~/MasterPage2.master" %>
<asp:Content ID="content2" ContentPlaceholderID=ContentPlaceHolder2 runat="server">
<asp:DataList ID="datalist2" runat="server"
onitemcommand="datalist2_ItemCommand" >
<FooterTemplate>
<section id="main" class="column" runat="server" style="width:900px;">
<article class="module width_full" style="width:900px;">
<header><h3 style="text-align: center">Shto Artikull </h3></header>
<div id="Div1" class="module_content" runat="server">
<asp:Label ID="Label1" runat="server" style="font-weight: 700">Tema</asp:Label>
<fieldset>
<asp:TextBox ID="txtTema" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorTema" runat="server"
ControlToValidate="txtTema" Display="Dynamic"
ErrorMessage="Kjo fushe eshte e nevojshme" style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset><br />
<asp:Label ID="Label6" runat="server" style="font-weight: 700">Abstrakti</asp:Label>
<fieldset>
<asp:TextBox ID="txtAbstrakti" style="height:250px;" Textmode="Multiline" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorAbstrakti" runat="server"
ControlToValidate="txtAbstrakti" ErrorMessage="Kjo fushe eshte e nevojshme"
style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset>
<asp:Label ID="lblData" runat="server" style="font-weight: 700">Data e Publikimit</asp:Label>
<fieldset>
<asp:TextBox ID="txtData" runat="server"></asp:TextBox>
</fieldset>
<asp:Label ID="lblKeywords" runat="server" style="font-weight: 700">Keywords</asp:Label>
<fieldset>
<asp:TextBox ID="txtKeywords" runat="server"></asp:TextBox>
</fieldset>
<br />
<asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
<div>
<asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Insert"
/>
</div><br />
<strong>Ngarko Artikull</strong><br />
<asp:FileUpload ID="FileUploadArtikull" runat="server" /><br />
<br />
<asp:Button ID="btnInsert" runat="server" CommandName="Insert" Text="Shto" />
</div>
</article>
</section>
</FooterTemplate>
</asp:DataList>
</asp:Content>
It shows this error:
Compiler Error Message: CS0103: The name 'e' does not exist in the
current context
In this line:
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
In your bind method you are calling an object e that doesn't exist. If the dropdownlist isn't inside a bound element, you can just reference the front code directly, e.g.
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
without finding the control as long as it is runat="server"
UPDATE
Okay, so you need to add an OnItemCreated event in your datalist
OnItemCreated="datalist2_OnItemCreated"
Then in that method you need this
protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
}
That will work for if you only have the footer, if you add an itemtemplate then you just need to get rid of the check for the footer and on each item creation grab that dropdownlist for that item
my 2nd dropdownlist is select financial year has years associated with it and when i am trying to select and year like 2011-2012 its not showing its value on button click instead its changing my selection to 1st one that is 2010-2011 same is happening if i select any other project code from my 1st dropdown i m able to select the 1st value in 2nd dropdownlist not the 2nd item?.....[whats happening is my 2nd dropdown which is showing values linked to my1st dropdownlist is not letting me select its 2nd value and submit if i m selecting the 2 nd value its automatically changing it to 1st value and displaying the result ?]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class Default2 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
if (Page.IsPostBack == false)
{
string query = "select * from project";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataValueField = ds.Tables[0].Columns[0].ToString();
DropDownList1.DataTextField = ds.Tables[0].Columns[1].ToString();
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "--Select--");
cmd.Dispose();
}
con.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
string query1 = "Select * from yearly where pid = " + DropDownList1.SelectedItem.Value.ToString();
SqlCommand cmd = new SqlCommand(query1, con);
DataSet ds = new DataSet();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
DropDownList2.DataSource = ds;
DropDownList2.DataValueField = ds.Tables[0].Columns[0].ToString();
DropDownList2.DataTextField = ds.Tables[0].Columns[1].ToString();
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, "--Select--");
cmd.Dispose();
}
catch (Exception)
{
}
con.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
try
{
SqlDataAdapter da = new SqlDataAdapter("select pcode,fyyear,date,salary,ta,contigency,nrc,institcharges,others from monthly where pcode=('" + DropDownList1.SelectedItem.ToString() + "' ) AND fyyear=('" + DropDownList2.SelectedItem.ToString() + "')",con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
}
i am also attaching aspx code:
<%# Page Title="" Language="C#" MasterPageFile="~/grid.master" AutoEventWireup="true" CodeFile="yearwiseex.aspx.cs" Inherits="Default2" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Label ID="Label1" runat="server" Text="Select Project Code"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server"
Height="20px" Width="130px"
onselectedindexchanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True"> </asp:DropDownList>
<asp:Label ID="Label2" runat="server" Text="Select Financial Year"></asp:Label>
<asp:DropDownList ID="DropDownList2" runat="server"
Height="20px" Width="130px"></asp:DropDownList>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Button" />
<br />
<br />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" style="margin-left: 82px"
Width="90%" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None"
BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical">
<AlternatingRowStyle BackColor="White" />
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
<br />
<br />
</asp:Content>
I think you're looking for MultiSelect. In that case, use a listbox:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listbox.aspx
...and set the selection mode to "Multiple".