Display data by claim numbers on grid view page - c#

I am using C#. net and SQL server 2005.
I am uploading files (Word, PDF) into the database, and displaying on page using grid view.
I have different claim numbers, like co50000006 (like 10 rows). I mean the claim number has different files. I have other claim numbers on my table. (like c08000131, c01000001).
I want to display only one claim number rows on grid. I mean what ever number my querystring show I want to display the particular claim number on my grid.(Request.QueryString["ClaimNum"];).
Please help me with this.
I am getting claimnumber on table on my page header and I am inserting this value into the table.
protected void Page_Load(object sender, EventArgs e)
{
//Showing Claim Number on file upload.
lblFileUploadCliamNumber.Text = Request.QueryString["ClaimNum"];
}
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource1" AllowPaging="True">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"
InsertVisible="False" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="ClaimNumber" HeaderText="Claim Number"
SortExpression="ClaimNumber" />
<asp:TemplateField HeaderText="Load Date">
<ItemTemplate>
<asp:Label runat="server" ID="LoadDate"
Text='<%# String.Format("{0:M/d/yyyy}", Eval("LoadDate")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="ContentType" HeaderText="ContentType"
SortExpression="ContentType" />
<asp:TemplateField HeaderText="Data">
<ItemTemplate>
<%--<asp:Image ID="Image1" runat="server"
ImageUrl='<%# "FileUploadHandler.ashx?ID=" + Eval("ID")%>'/>--%>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick = "Retreive_Doc">Download</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am using a SQL query here:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ AppSettings:connString %>"
SelectCommand="SELECT [ID], [ClaimNumber], [LoadDate], [Description], [ContentType], [Data]
FROM [tblFiles]"></asp:SqlDataSource>
Below are the my total code using in file upload.aspx.cs.
public partial class FileUpload : System.Web.UI.Page
{
private string redirectFrom = "FileUpload";
protected void Page_Load(object sender, EventArgs e)
{
//Showing Claim Number on file upload.
lblFileUploadCliamNumber.Text = Request.QueryString["ClaimNum"];
}
protected void Page_Init(object sender, EventArgs e)
{
WireEvents();
}
private void WireEvents()
{
btnFileUploadClose.Click += new EventHandler(btnFileUploadClose_Click);
}
private void btnFileUploadClose_Click(object sender, EventArgs e)
{
ReturnToClaimInfo();
}
private void ReturnToClaimInfo()
{
Response.Redirect(String.Format("/ClaimInfoView.aspx?ClaimNum={0}&ClaimCertSeqNo={1}&ClaimCovNum={2}&RedirectedFrom={3}"
, Request.QueryString["ClaimNum"]
, Request.QueryString["ClaimCertSeqNo"]
, Request.QueryString["ClaimCovNum"]
, redirectFrom));
}
/// Different file types start
protected void btnUpload_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
string strClaimNumber = lblFileUploadCliamNumber.Text.ToUpper();
string strDate = DateTime.Now.ToShortDateString();
string strDescription = txtDescription.Text.ToString();
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data, Description, ClaimNumber, LoadDate)" +
" values (#Name, #ContentType, #Data, #Description, #ClaimNumber, #LoadDate)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value
= contenttype;
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
cmd.Parameters.Add("#Description", SqlDbType.VarChar).Value = strDescription.ToString();
cmd.Parameters.Add("#ClaimNumber", SqlDbType.NVarChar).Value = strClaimNumber.ToUpper();
cmd.Parameters.Add("#LoadDate", SqlDbType.DateTime).Value = strDate.ToString();
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
if (lblMessage.Text == "File Uploaded Successfully")
{
txtDescription.Text = string.Empty;
}
//if(FileUpload1 != null)
//{
// lblMessage.Text = string.Empty;
//}
GridView1.DataBind();
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." +
" Upload Word/PDF/Excel formats";
}
}
private Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager
.AppSettings["connString"];
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
//Retrieve doc
protected void Retreive_Doc(object sender, EventArgs e)
{
string strQuery = "select Name, ContentType, Data from tblFiles where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = ((LinkButton) sender).CommandArgument;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
// Get data
public DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager
.AppSettings["connString"];
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
// download file
public void download(DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
//end
}
}

Have you considered
SelectCommand="SELECT [ID], [ClaimNumber], [LoadDate], [Description], [ContentType], [Data] FROM [tblFiles] where [ClaimNumber] = " Request.QueryString["ClaimNum"]>

Related

How to view byte image in a gridview in asp.net?

I want to view the image in gridview from dataBase. In dataBase the image is in byte formate. How to retrieve and view that images in grid View. I don't know how to code for this.Anyone know help me to solve the issue.
To display image in gridview from database.the image is in byte
format.How to view that bytecode as image in gridview
Here is my code:
//Image Upload Code Here//
protected void Add_Click(object sender, EventArgs e)
{
if (!FileUpload1.HasFile)
{
Label2.Visible = true;
Label2.Text = "Please Select Image File"; //checking if file uploader has no file selected
}
else
{
int length = FileUpload1.PostedFile.ContentLength;
byte[] pic = new byte[length];
FileUpload1.PostedFile.InputStream.Read(pic, 0, length);
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
// SqlCommand cmd1 = new SqlCommand("insert into Student" + "(RegNo,Name,DOB,Gender,Address,Country,Picture) values(#RegNo,#Name,#DOB,#Gender,#Address,#Country,#photo)", con);
SqlCommand cmd1 = new SqlCommand("sp", con);
cmd1.CommandType = CommandType.StoredProcedure;
con.Open();
cmd1.Parameters.AddWithValue("#RegNo", RegNo.Text);
cmd1.Parameters.AddWithValue("#Name", Name.Text);
cmd1.Parameters.AddWithValue("#DOB", Dob.Text);
cmd1.Parameters.AddWithValue("#gender", Gender.SelectedValue);
cmd1.Parameters.AddWithValue("#Address", Address.Text);
cmd1.Parameters.AddWithValue("#Country", Country.Text);
//cmd1.Parameters.AddWithValue("#datetime", DateTime.Now);
cmd1.Parameters.AddWithValue("#Picture", pic);
try
{
cmd1.ExecuteNonQuery();
Label2.Visible = true;
Label2.Text = "Image Uploaded Sucessfully";
con.Close();//after Sucessfully uploaded image
}
catch(Exception ex)
{
throw ex;
}
}
Response.Redirect("~/WebForm1.aspx");
}
}
Actually there is no event with name ItemdataBound for gridview. For gridview use RowDataBound event instead. Below is the sample implementation for the same.
ASPX:
<asp:GridView runat="server" ID="grd" OnRowDataBound ="grd_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="image">
<ItemTemplate>
<img src='<%# Eval("imagedata") %>' id="imageControl" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS:
protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
System.Web.UI.HtmlControls.HtmlImage imageControl = (System.Web.UI.HtmlControls.HtmlImage)e.Row.FindControl("imageControl");
if (((DataRowView)e.Row.DataItem)["imagedata"] != DBNull.Value)
{
imageControl.Src = "data:image/png;base64," + Convert.ToBase64String((byte[])(((DataRowView)e.Row.DataItem))["imagedata"]);
}
}
}
You can use ItemDataBound event of grid view as given below:
if(e.Item.ItemType ==ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Web.UI.HtmlControls.HtmlImage imageControl =(System.Web.UI.HtmlControls.HtmlImage) e.Item.FindControl("imageControl");
if (((DataRowView)e.Item.DataItem)["imagedata"] != DBNull.Value)
{
imageControl.Src = "data:image/png;base64,"+ Convert.ToBase64String((byte[])((DataRowView)e.Item.DataItem)["imagedata"]) ;
}
}
First find the image control inside your grive view and set it's image source property to "data:image/png;base64,"+ Convert.ToBase64String((byte[])((DataRowView)e.Item.DataItem)["imagedata"]) ;
Note: imagedata should be the name of column you used to save image.

download link for asp not working

I am using the download link for my upload and download method in my ASP.NET Project. i created a database with fields
tFileName (nvarchar 100) , tFileupload (nvarchar 100), tFileData (varbinary (max)).
The data saves when I upload it and the fields are being saved. My problem is I can't seem to download the data from the database.
ill be posting my code and my c# codes. hope someone can help me. thanks!
My asp.net code, this code is inside my UpdatePanel also.
<asp:GridView ID="gvFile" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000" CellPadding="5">
<Columns>
<asp:BoundField DataField="tFileName" HeaderText="File Name" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="lnkDownload_Click" CommandArgument='<%# Eval("TravelNumber") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here is my code for my aspx.cs
public void getFile()
{
Utility u = new Utility();
string conn = u.local();
using (SqlConnection connUser = new SqlConnection(conn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select TravelNumber, tFileName from TravelTransaction";
cmd.Connection = connUser;
connUser.Open();
gvFile.DataSource = cmd.ExecuteReader();
gvFile.DataBind();
connUser.Close();
}
}
}
protected void lnkDownload_Click(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string fileName, contentType;
Utility u = new Utility();
string conn = u.local();
using (SqlConnection connUser = new SqlConnection(conn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select tFileName, tFileUpload, tFileData from TravelTransaction where TravelNumber = #Trav";
cmd.Parameters.Add(new SqlParameter("#Trav", id));
cmd.Connection = connUser;
connUser.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["tFileData"];
contentType = sdr["tFileUpload"].ToString();
fileName = sdr["tFileName"].ToString();
}
connUser.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("content-disposition", "attachment;filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
I can't seem to find my error, actually there is no errors in it. But the file does not download and no action are happening. What is wrong with my code?

how to get column data when check box is checked using data list in asp.net

this is eswar.k , i have one problem in asp.net..that is ..
i have one datalist .that is shows data from database ..that is contains .check box,image,and lables..here what is the problem .. when i am checked on check box ,i have to display the email labels into the text box..(like multiple recipients eg:eswar#gmil.com,eee#yahoo.in..etc )
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strconnstring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
string strquery = "select chid,chname,chlanguage,chrating,chemail,contenttype,data from tbl_channel_join Order by chid";
SqlCommand cmd = new SqlCommand(strquery);
SqlConnection con = new SqlConnection(strconnstring);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
//GridView1.DataSource = dt;
//GridView1.DataBind();
//GridView2.DataSource = dt;
//GridView2.DataBind();
dl_channels.DataSource = dt;
dl_channels.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
Let's say you have a Gridview with checkbox like this :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkIT" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:Button ID="btnDisplay" runat="server" Text="Show data selected" OnClick="btnDisplay_Click"/>
<asp:TextBox id="textboxDataDisplay" runat="server" />
with a button to show the selected checkbox columns
C# code
protected void btnDisplay_Click(object sender, EventArgs e)
{
string data = "";
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
string yourFirstRowCell = row.Cells[1].Text;
string yourSecondRowCell = row.Cells[2].Text;
string yourThirdRowCell = row.Cells[3].Text;
data = yourFirstRowCell + yourSecondRowCell + yourThirdRowCell;
}
}
}
textboxDataDisplay.text = data;
}
Row cells are the cells in that row you want to get where the checkbox is checked.

Make ASP Validators validate just one gridview row?

I am making a little website for myself and within this website you can make users. The moment you add a user it goes into a database. You can also see the existing users in a gridview, so when you make a new user it goes into the gridview. But one little problem, when I try and use validators within this gridview, it validates every row. I need it to validate just one row. Someone said something about row ID, but i don't know how to make that work.
As you can see I've tried some stuff with RowIndex, but couldn' t get it to work
Any help is appreciated
Management.Aspx :
<asp:GridView runat="server" ID="gridUsers" AutoGenerateColumns="False" DataKeyNames="username" DataSourceID="DSUserList" OnRowCommand="gridUsers_RowCommand">
<Columns>
<asp:BoundField DataField="username" HeaderText="Gebruikersnaam" ReadOnly="True" SortExpression="username"></asp:BoundField>
<asp:BoundField DataField="display_name" HeaderText="Naam" SortExpression="display_name"></asp:BoundField>
<asp:TemplateField >
<ItemTemplate>
<asp:Button OnClientClick="ConfirmDeleteAdmin()" Text="Verwijderen" runat="server" id="btnDeleteUser" CommandName="delUser" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" id="txtChangePassword" />
<%-- TODO: Mike: Validators via code --%>
<asp:Button OnClientClick="ConfirmChangePassword()" ValidationGroup="vgChangePW" Text="Wachtwoord wijzigen" runat="server" ID="btnChangePassword" CommandName="changePassword" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<%-- <asp:RequiredFieldValidator ID="rfChangePassReq" ControlToValidate="<%# String.Format("txtChangePW{0}",((GridViewRow) Container).RowIndex).ToString() %>" ValidationGroup="vgChangePW" runat="server" ErrorMessage="<br/>U heeft geen nieuw wachtwoord ingevoerd"></asp:RequiredFieldValidator>--%>
<%-- asp:RegularExpressionValidator ID="rfChangePassReg" ValidationExpression="^(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$" ControlToValidate="<%# String.Format("txtChangePW{0}",((GridViewRow) Container).RowIndex).ToString() %>" ValidationGroup="vgChangePW" runat="server" ErrorMessage="<br/>Uw wachtwoord moet uit minimaal 6 tekenen bestaan en moet minimaal 1 hoofdletter en 1 cijfer bevatten"></asp:RegularExpressionValidator>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Management.aspx.cs :
protected void btnCreateUser_Click(object sender, EventArgs e)
{
try {
connection.Open();
} catch (Exception) {}
String password = txtPassword.Text.Trim();
password = password != "" ? ProjectManager.GetSHA1HashData(password) : "";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.CommandText = "sp_add_user";
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 100).Value = txtUsername.Text;
cmd.Parameters.Add("#password", SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("#displayName", SqlDbType.NVarChar, 100).Value = txtDisplayName.Text;
cmd.Parameters.Add("#return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int code = int.Parse(cmd.Parameters["#return_value"].Value.ToString());
if (code == 0)
{
lblNewUserStatus.Text = "Gebruiker bestaat al";
lblNewUserStatus.ForeColor = Color.Red;
}
else
{
DSUserList.EnableCaching = false;
gridUsers.DataBind();
DSUserList.EnableCaching = true;
lblNewUserStatus.Text = "Gebruiker toegevoegd";
lblNewUserStatus.ForeColor = Color.Black;
txtUsername.Text = "";
txtPassword.Text = "";
txtDisplayName.Text = "";
}
connection.Close();
}
protected void gridUsers_RowCommand(object sender, GridViewCommandEventArgs e)
{
// Deletes user or changes a password of a user
if (e.CommandName == "delUser")
{
string confirmValue = Request.Form["delete_admin"];
if (confirmValue == "Yes") {
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gridUsers.Rows[index];
String usernameToDelete = row.Cells[0].Text;
try {
connection.Open();
} catch (Exception) { }
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.CommandText = "sp_delete_user";
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 100).Value = usernameToDelete;
cmd.Parameters.Add("#return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int code = int.Parse(cmd.Parameters["#return_value"].Value.ToString());
if (code == 0) {
//Failed
lblDelteStatus.Text = "Kan gebruiker admin niet verwijderen";
lblDelteStatus.ForeColor = Color.Red;
} else {
// Deleted
lblDelteStatus.Text = "Gebruiker verwijderd";
lblDelteStatus.ForeColor = Color.Black;
// Reload user list
DSUserList.EnableCaching = false;
gridUsers.DataBind();
DSUserList.EnableCaching = true;
}
connection.Close();
if (usernameToDelete == Session["username"].ToString()) {
ProjectManager.logout();
Page.Response.Redirect(Page.Request.Url.ToString());
}
}
}
else if (e.CommandName == "changePassword")
{
string confirmValue = Request.Form["change_password"];
if (confirmValue == "Yes") {
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gridUsers.Rows[index];
String username = row.Cells[0].Text;
TextBox txtPassword = (TextBox)row.Cells[3].FindControl("txtChangePassword");
String password = txtPassword.Text.Trim();
password = password != "" ? ProjectManager.GetSHA1HashData(password) : "";
try {
connection.Open();
} catch (Exception) { }
cmd.Connection = connection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_change_password";
cmd.Parameters.Add("#password", SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 100).Value = username;
cmd.Parameters.Add("#return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int code = int.Parse(cmd.Parameters["#return_value"].Value.ToString());
if (code == 0) {
lblDelteStatus.Text = "Dit wachtwoord is onlangs gebruikt, kies een ander wachtwoord";
lblDelteStatus.ForeColor = Color.Red;
} else if (code == 1) {
lblDelteStatus.Text = "Wachtwoord gewijzigd";
lblDelteStatus.ForeColor = Color.Black;
}
connection.Close();
}
}
}
Try this in the RowDataBound event:
Create a row specific validation group name that is a concatenation of some prefix and the row index and assign it to each validator and control in the row that is part of the validation group... i.e.:
valGroupName = string.format("vgRow{0}", e.row.rowindex.tostring);
Button btn = e.row.FindControl("btnChangePassword");
btn.ValidationGroup = valGroupName
RequiredFieldValidator vreq = e.row.FindControl("rfChangePassReq");
vreq.ValidationGroup = valGroupName
RegularExpressionValidator vregx = e.row.FindControl("rfChangePassReg");
vregx.ValidationGroup = valGroupName
...etc...
This way only validation for the specific row should be triggered when you select the row button to save.
I don't recall and I can't test it right now, but you may have an issue with any field that is connected to a RequiredFieldValidator, it may prevent posting. You'll have to check that out. You might be ok as they will be part of a different validation group.

How to keep check box checked after button click for update

Please help me to keep checkbox is checked after checking checkbox for updating corresponding row in Gridview.this my complete source code.Please help Me to keep checkbox inside Gridview checked after update button click.I met scenario that in order to identify which user's data going to be update so.Please help me friends.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID" onpageindexchanging=" grvDetails_PageIndexChanging">
<Columns>
<asp:TemplateField HeaderText="Page">
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" onclick = "checkAll(this);"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="radID" runat="server" onclick ="CheckSingleCheckbox(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"/>
<asp:BoundField DataField="FirstName" HeaderText="FirstName"/>
<asp:BoundField DataField="LastName" HeaderText="LastName"/>
<asp:BoundField DataField="Gender" HeaderText="Gender"/>
<asp:BoundField DataField="Email" HeaderText="Email"/>
<asp:BoundField DataField="Phone" HeaderText="Phone"/>
<asp:BoundField DataField="ContactAddres" HeaderText="ContactAddres"/>
<asp:BoundField DataField="State" HeaderText="ContactState"/>
<asp:BoundField DataField="Country" HeaderText="ContactCountry"/>
<asp:BoundField DataField="CommunicationAddress" HeaderText="CommunicationAddress"/>
<asp:BoundField DataField="State1" HeaderText="CommunicationState"/>
<asp:BoundField DataField="Country1" HeaderText="CommunicationCountry"/>
<asp:BoundField DataField="statec" HeaderText="ContactCountry" ShowHeader="false" />
<asp:BoundField DataField="countryc" HeaderText="CommunicationAddress" ShowHeader="false" />
<asp:BoundField DataField="CommunicationState" HeaderText="CommunicationState" ShowHeader="false" />
<asp:BoundField DataField="CommunicationCountry" HeaderText="CommunicationCountry" ShowHeader="false" />
</Columns>
</asp:GridView>
And this is my c# page and I'm posting code for update
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Collections;
namespace Reg
{
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gridView();
populate1();
populate2();
}
}
public void populate1()
{
DataSet ds = new DataSet();
SqlConnection con;
SqlCommand cmd = new SqlCommand();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
SqlCommand com = new SqlCommand("select *from CountryDetail", con);
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(ds);
ddlCountryPermanent.DataTextField = ds.Tables[0].Columns["Country"].ToString();
ddlCountryPermanent.DataValueField = ds.Tables[0].Columns["CID"].ToString();
ddlCountryPermanent.DataSource = ds.Tables[0];
ddlCountryPermanent.DataBind();
ddlCountryPermanent.Items.Insert(0, "Select");
ddlCountryCommunication.DataTextField = ds.Tables[0].Columns["Country"].ToString();
ddlCountryCommunication.DataValueField = ds.Tables[0].Columns["CID"].ToString();
ddlCountryCommunication.DataSource = ds.Tables[0];
ddlCountryCommunication.DataBind();
ddlCountryCommunication.Items.Insert(0, "Select");
}
public void populate2()
{
DataSet ds = new DataSet();
SqlConnection con;
SqlCommand cmd = new SqlCommand();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
SqlCommand com = new SqlCommand("select *from StatesDetail", con);
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(ds);
ddlStatePermanent.DataTextField = ds.Tables[0].Columns["State"].ToString();
ddlStatePermanent.DataValueField = ds.Tables[0].Columns["SID"].ToString();
ddlStatePermanent.DataSource = ds.Tables[0];
ddlStatePermanent.DataBind();
ddlStatePermanent.Items.Insert(0, "Select");
ddlStateCommunication.DataTextField = ds.Tables[0].Columns["State"].ToString();
ddlStateCommunication.DataValueField = ds.Tables[0].Columns["SID"].ToString();
ddlStateCommunication.DataSource = ds.Tables[0];
ddlStateCommunication.DataBind();
ddlStateCommunication.Items.Insert(0, "Select");
}
protected void saveButton_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlConnection con;
SqlCommand cmd = new SqlCommand();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
cmd = new SqlCommand("proc_Registers", con);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
if (RdoGender.SelectedItem.Value == "0")
{
cmd.Parameters.AddWithValue("#Gender", "0");
}
else
{
cmd.Parameters.AddWithValue("#Gender", "1");
}
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("#ContactAddres", txtAddressCon.Text);
var statcon = ddlStatePermanent.SelectedItem.Value;
cmd.Parameters.AddWithValue("#ContactState", statcon);
var ddlCourtyCon = ddlCountryPermanent.SelectedItem.Value;
cmd.Parameters.AddWithValue("#ContactCountry", ddlCourtyCon);
cmd.Parameters.AddWithValue("#CommunicationAddress", txtAddressPer.Text);
var statper = ddlStateCommunication.SelectedItem.Value;
cmd.Parameters.AddWithValue("#CommunicationState", statper);
var ddlCourtyPer = ddlCountryCommunication.SelectedItem.Value;
cmd.Parameters.AddWithValue("#CommunicationCountry", ddlCourtyPer);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
gridView();
}
public void gridView()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("proc_FinalDataGridviewNew", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.PageSize = 5;
GridView1.Columns[1].Visible = true;
GridView1.Columns[13].Visible = true;
GridView1.Columns[14].Visible = true;
GridView1.Columns[15].Visible = true;
GridView1.Columns[16].Visible = true;
Page.DataBind();
GridView1.Columns[1].Visible = false;
GridView1.Columns[13].Visible = false;
GridView1.Columns[14].Visible = false;
GridView1.Columns[15].Visible = false;
GridView1.Columns[16].Visible = false;
}
protected void grvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
DataBind();
gridView();
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[13].Visible = false;
e.Row.Cells[14].Visible = false;
e.Row.Cells[15].Visible = false;
e.Row.Cells[16].Visible = false;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
var chk = row.FindControl("radID") as CheckBox;
if (chk.Checked)
{
var ID = row.Cells[1].Text;
var fname = row.Cells[2].Text;
var lname = row.Cells[3].Text;
var gendr = row.Cells[4].Text;
var mail = row.Cells[5].Text;
var phne = row.Cells[6].Text;
var addrscon = row.Cells[7].Text;
var statecon = row.Cells[13].Text;
var countrycon = row.Cells[14].Text;
var addrsper = row.Cells[10].Text;
var stateper = row.Cells[15].Text;
var countryper = row.Cells[16].Text;
txtID.Text = ID;
txtFirstName.Text = fname;
txtLastName.Text = lname;
string gndr;
if (gendr == "Male")
{
gndr = "0";
}
else
{
gndr = "1";
}
RdoGender.SelectedValue = gndr;
txtEmail.Text = mail;
txtPhone.Text = phne;
txtAddressCon.Text = addrscon;
ddlStatePermanent.SelectedValue = statecon;
ddlCountryPermanent.SelectedValue = countrycon;
txtAddressPer.Text = addrsper;
ddlStateCommunication.SelectedValue = stateper;
ddlCountryCommunication.SelectedValue = countryper;
DataBind();
gridView();
}
else
{
lblMessage.Text = "*Please select any row to Update";
}
}
}
protected void updateButton_Click(object sender, EventArgs e)
{
string id = txtID.Text;
string fname = txtFirstName.Text;
string lname = txtLastName.Text;
string gendr = RdoGender.Text;
string mail = txtEmail.Text;
string phne = txtPhone.Text;
string addrscon = txtAddressCon.Text;
string statecon = ddlStatePermanent.SelectedItem.Value;
string countrycon = ddlCountryPermanent.SelectedItem.Value;
string addrsper = txtAddressCon.Text;
string stateper = ddlStateCommunication.SelectedItem.Value;
string countryper = ddlCountryCommunication.SelectedItem.Value;
SqlConnection con = con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("proc_UpdateRegisters", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Id", id);
cmd.Parameters.AddWithValue("#FirstName", fname);
cmd.Parameters.AddWithValue("#LastName", lname);
cmd.Parameters.AddWithValue("#Gender", gendr);
cmd.Parameters.AddWithValue("#Email", mail);
cmd.Parameters.AddWithValue("#Phone", phne);
cmd.Parameters.AddWithValue("#ContactAddres", addrscon);
cmd.Parameters.AddWithValue("#ContactState", statecon);
cmd.Parameters.AddWithValue("#ContactCountry", countrycon);
cmd.Parameters.AddWithValue("#CommunicationAddress", addrsper);
cmd.Parameters.AddWithValue("#CommunicationState", stateper);
cmd.Parameters.AddWithValue("#CommunicationCountry", countryper);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
DataTable dt = new DataTable();
cmd.CommandType = CommandType.StoredProcedure;
con.Close();
gridView();
}
// row delete
protected void btnDelete_Click(object sender, EventArgs e)
{
StringCollection idCollection = new StringCollection();
string strID = string.Empty;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)GridView1.Rows[i].
Cells[0].FindControl("radID");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = GridView1.Rows[i].Cells[1].Text;
idCollection.Add(strID);
}
}
}
if (idCollection.Count > 0)
{
DeleteMultipleRecords(idCollection);
GridView1.DataBind();
}
else
{
lblMessage.Text = "*Please select any row to delete";
}
DataBind();
gridView();
}
private void DeleteMultipleRecords(StringCollection idCollection)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
SqlCommand cmd = new SqlCommand();
string IDs = "";
foreach (string id in idCollection)
{
IDs += id.ToString() + ",";
}
try
{
string test = IDs.Substring
(0, IDs.LastIndexOf(","));
string sql = "Delete from Registers" + " WHERE ID in (" + test + ")";
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
con.Close();
}
}
protected void polyuria2_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
var peradrs = txtAddressCon.Text;
var stat = ddlStatePermanent.SelectedIndex;
var contry = ddlCountryPermanent.SelectedIndex;
txtAddressPer.Text = peradrs;
ddlStateCommunication.SelectedIndex = stat;
ddlCountryCommunication.SelectedIndex = contry;
}
}
}
}
This is because the ViewState unable to maintain CheckBox state from GridView column. Easiest solution will be:
Add 'OnCheckedChanged' and 'OnDataBinding' event for checkbox column
<ItemTemplate>
<asp:CheckBox ID="radID" runat="server" OnCheckedChanged="radID_CheckedChanged" OnDataBinding="radID_DataBinding" />
</ItemTemplate>
Next step will be implement these events:
protected void radID_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkbox = (CheckBox)sender;
if (checkbox.Checked)
{
ViewState[checkbox.UniqueID] = true;
}
else
{
ViewState.Remove(checkbox.UniqueID);
}
}
protected void radID_DataBinding(object sender, EventArgs e)
{
CheckBox checkbox = (CheckBox)sender;
checkbox.Checked = ViewState[checkbox.UniqueID] != null;
}
Please let me know, if this helps.

Categories