I have a gridview as below
<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" AllowSorting="True"
OnSelectedIndexChanged="gvDoctorList_SelectedIndexChanged" OnRowCommand="gvDoctorList_RowCommand" OnRowDataBound="gvDoctorList_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%--<asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged" AutoPostBack="true" />--%>
<asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'></asp:Label>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandArgument='<%# Eval("PatientId") %>' CommandName = "Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PatientId" HeaderText="PatientId" SortExpression="PatientId" />
<asp:BoundField DataField="firstname" HeaderText="firstname" SortExpression="firstname" />
<asp:BoundField DataField="lastname" HeaderText="lastname" SortExpression="lastname" />
<asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>"
SelectCommand="SELECT [PatientId],[firstname], [lastname], [sex] FROM [PatientDetails]"></asp:SqlDataSource>
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" />
Code behind gridview rowcommand is as below
protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int pID = Convert.ToInt32(e.CommandArgument);
Session["PatientId"] = Convert.ToString(e.CommandArgument);
//Server.Transfer("Patientstaticformatrix.aspx");
string pIDstr = Convert.ToString(Session["PatientId"]);
if (!string.IsNullOrEmpty(pIDstr))
{
int patientID = Convert.ToInt32(pID);
//string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
string sqlquery = "SELECT * FROM [MyDatabase].[dbo].[PatExam] where PId = '" + patientID + "'";
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using(SqlConnection conn = new SqlConnection(connection))
{
//SqlConnection conn = new SqlConnection(con);
DataSet ds;
ds = new DataSet();
SqlDataAdapter cmpatientexam;
conn.Open();
cmpatientexam = new SqlDataAdapter(sqlquery, conn);
cmpatientexam.Fill(ds, "PatientExam");
TreeNode pidnode = new TreeNode();
pidnode.Text = pIDstr;
foreach (DataRow patrow in ds.Tables["PatientExam"].Rows)
{
//TreeNode tvpatexam = new TreeNode();
//tvpatexam.Text = patrow["PId"].ToString();
//TreeView1.Nodes.Add(tvpatexam);
//for (int i = 0; i < ds.Tables["PatientExam"].Columns["PId"].Count; i++)
//if (patrow["PId"].ToString() != DBNull.Value)
//{
TreeNode childtvpatexam = new TreeNode();
childtvpatexam.Text = patrow["Exam"].ToString();
pidnode.ChildNodes.Add(childtvpatexam);
//break;
//}
//TreeView1.Nodes.Add(tvpatexam);
}
TreeView1.Nodes.Add(pidnode);
ds.Dispose();
cmpatientexam.Dispose();
conn.Close();
conn.Dispose();
}
}
}
}
Code behind the button click event is as below
protected void btnformatric_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvDoctorList.Rows)
{
Button btn = (Button)row.FindControl("Select");
if (btn != null)
{
string pIDstr = Convert.ToString(Session["PatientId"]);
string exam = ((Button)sender).Text;
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PatExam]([PId],[Exam]) VALUES (#pid,#exam)", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#pid", pIDstr);
cmd.Parameters.AddWithValue("#exam", exam);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write("Error Occured: " + ex.Message.ToString());
}
finally
{
con.Close();
cmd.Dispose();
}
}
}
}
I want to insert the value which is selected from gridview using select button and insert that selected value on button click event....but with the above code it is not working...
Can anyone suggest me some other idea or if possible with these code then how...can you give me the code for it....Thanks a lot
You can add a hidden field and save Gridview's rowindex in the hidden field. In btnformatric_Click you can get the row by index and get the data. The markup:
<asp:HiddenField ID="hdnRowIndex" runat="server" Value ="" />
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" />
In code, gvDoctorList_RowCommand method:
protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int pID = Convert.ToInt32(e.CommandArgument);
Session["PatientId"] = Convert.ToString(e.CommandArgument);
//Server.Transfer("Patientstaticformatrix.aspx");
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
hdnRowIndex.Value = gvr.RowIndex.ToString();
... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
btnformatric_Click method:
protected void btnformatric_Click(object sender, EventArgs e)
{
int rowIndex = 0;
if (int.TryParse(hdnRowIndex.Value, out rowIndex))
{
//Get the row
GridViewRow row = gvDoctorList.Rows[rowIndex];
Button btn = (Button)row.FindControl("Select");
if (btn != null)
{
string pIDstr = Convert.ToString(Session["PatientId"]);
string exam = ((Button)sender).Text;
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PatExam]([PId],[Exam]) VALUES (#pid,#exam)", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#pid", pIDstr);
cmd.Parameters.AddWithValue("#exam", exam);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write("Error Occured: " + ex.Message.ToString());
}
finally
{
con.Close();
cmd.Dispose();
}
}
}
}
I presume that you're interested in inserting a record based on the selected PatientID value from the GridView?
What you want to do is start by setting the GridView's DataKeyNames property to PatientID like so:
<asp:GridView ID="gvDoctorList" runat="server" DataKeyNames="PatientID" ...>
Then in the btnformatric_Click event handler you can get the selected PatientID value via gvDoctorList.SelectedValue, as in:
string pIDstr = gvDoctorList.SelectedValue.ToString();
Of course, before you do the above you should check to make sure that the user has selected a patient from the grid (namely, that gvDoctorList.SelectedIndex >= 0).
Related
I work on asp.net web forms with c# I need to add checkbox column as last column on gridview
but i don't know how to add it
static string con =
"Data Source=DESKTOP-L558MLK\\AHMEDSALAHSQL;" +
"Initial Catalog=UnionCoop;" +
"User id=sa;" +
"Password=321;";
SqlConnection conn = new SqlConnection(con);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridViewSearch.DataSource = GetDataForSearch();
GridViewSearch.DataBind();
}
}
public DataTable GetDataForSearch()
{
string response = string.Empty;
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select top 10 datelogged AS EntredDatetime, Doc_type AS OrderType, Printer_name, BranchID AS BranchCode, id from Print_Report";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 50000;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
catch (Exception ex)
{
response = ex.Message;
}
finally
{
cmd.Dispose();
conn.Close();
}
return dt;
}
on aspx page
<asp:GridView ID="GridViewSearch" runat="server">
</asp:GridView>
GridViewSearch.DataSource = GetDataForSearch();
DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "X";
checkColumn.HeaderText = "X";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
GridViewSearch.Columns.Add(checkColumn);
GridViewSearch.DataBind();
I get error on line below
GridViewSearch.Columns.Add(checkColumn);
argument 1 can't convert from system.windows.forms.datagridviewcheckbox to system.web.ui.webcontrol.databoundfield
so how to solve this issue please ?
Seems to me, that if you want say a button, or check box, or dropdown?
why not just add it to the markup.
So, say like this:
<div id="MyGridPick" runat="server" style="display:normal;width:40%">
<asp:Label ID="lblSel" runat="server" Text="" Font-Size="X-Large"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" cssclass="table table-hover" OnRowDataBound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" ItemStyle-Width="120px" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
Then my code to load is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA ORDER BY HotelName");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
Now, of course I get VERY tired of typing that connection string stuff over and over. So, I have a "genreal" routine like this:
public DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
cmdSQL.Connection = conn;
using (cmdSQL)
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And the result of running above:
So, kind of hard to make the case to "add" a check box control, when you can just drop one into the gridview.
Same goes for a button, maybe we want a button to "view" or edit the above row, or some such.
So, once again, just drop in a plain jane button, say like this:
<asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Button ID="bView" runat="server" Text="View" CssClass="btn"
OnClick="bView_Click" />
</ItemTemplate>
</asp:TemplateField>
And now we have this:
And EVEN better?
Well, since that button (or check box) is a plain jane standard control?
then you can add standard events, like a click event, or whatever you want.
Say this code for the button click (shows how to get current row).
protected void bView_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gRow = btn.NamingContainer as GridViewRow;
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA WHERE ID = #ID");
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
DataTable dtHotel = MyRstP(cmdSQL);
General.FLoader(MyEditArea, dtHotel.Rows[0]);
MyGridPick.Style.Add("display", "none"); // hide grid
MyEditArea.Style.Add("display", "normal"); // show edit div area
}
And we now get/see this:
Edit: Process each checked/selected row.
this:
protected void cmdSelProcess_Click(object sender, EventArgs e)
{
// process all rows in GV with check box
String sPK = "";
List<int> MySelected = new List<int>();
foreach (GridViewRow gRow in GridView1.Rows)
{
CheckBox chkSel = (CheckBox)gRow.FindControl("chkSel");
if (chkSel.Checked)
{
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
// add pk value of row to our list
MySelected.Add(PK);
// Or we could process data based on current gRow
if (sPK != "")
sPK += ",";
sPK += PK.ToString();
Debug.Print(PK.ToString());
}
}
// at this point, we have a nice list of selected in MySelected
// or, maybe process as a data table
SqlCommand cmdSQL =
new SqlCommand($"SELECT * FROM tblHotelsA where ID IN({sPK})");
DataTable rstSelected = MyRstP(cmdSQL);
//
foreach (DataRow dr in rstSelected.Rows)
{
// do whatever
}
}
Datagridviewcheckboxcolumn is a Windows formx object. You are working in web forms. Please see the link below for information on the webforms check box field
CheckBoxField checkColumn = new CheckBoxField();
I am using radio button inside gridivew. I want to select 1 radio button at a time not multiple. I tried this but not working i.e it disables the only selected one too.
protected void btnAward_CheckedChanged(object sender, EventArgs e)
{
try
{
foreach (GridViewRow gr in gvAppliedWorks.Rows)
{
int RowIndex = gr.RowIndex;
int AppliedWorkID = gvAppliedWorks.DataKeys[gr.RowIndex].Value.ToInt32();
RadioButton rdbtn = gr.FindControl("btnAward") as RadioButton;
if (rdbtn.Checked == true)
{
//if(RowIndex )
rdbtn.Checked = false;
}
}
}
catch (Exception ex)
{
Utility.Msg_Error(Master, ex.Message);
}
}
}
Try this code:
GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton runat="server" id="rbtn1" name="rbtn" GroupName="rgrp" onclick = "RadioCheck(this);" ></asp:RadioButton>
<asp:HiddenField ID="HiddenField1" runat="server" Value = '<%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code for filling gridview from DB
protected void bind()
{
using (SqlConnection con = new SqlConnection("Connection string"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tableName", con);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();
}
}
Finally add this script to avoid multiple selection
<script type = "text/javascript">
function RadioCheck(rb) {
var gv = document.getElementById("<%=GridView1.ID%>");
var rbs = gv.getElementsByTagName("input");
var row = rb.parentNode.parentNode;
for (var i = 0; i < rbs.length; i++) {
if (rbs[i].type == "radio") {
if (rbs[i].checked && rbs[i] != rb) {
rbs[i].checked = false;
break;
}
}
}
}
I am having a little trouble with paging in a nested grid view.
When I try to change page I am getting some very strange and unexpected behaviour. Sometimes it will post back but not actually change the page and sometimes it does change the page but not as expected, it is messing with the order so you will have some items from the previous page still.
My markup is as follows:
<asp:GridView
ID="grdImages"
runat="server"
AllowPaging="true"
ShowFooter="true"
PageSize="5"
AutoGenerateColumns="false"
OnPageIndexChanging="grdImages_PageIndexChanging"
OnRowCancelingEdit="grdImages_RowCancelingEdit"
OnRowCommand="grdImages_RowCommand"
OnRowEditing="grdImages_RowEditing"
OnRowUpdating="grdImages_RowUpdating"
OnRowDeleting="grdImages_RowDeleting"
EmptyDataText="No Data Available at this Time"
OnRowDataBound="grdImages_RowDataBound"
DataKeyNames="ProductId">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField AccessibleHeaderText="Product ID" HeaderText="Product ID" FooterText="Product ID">
<ItemTemplate>
<asp:Label ID="lblProdId" runat="server" Text='<%# Eval("ProductId") %>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdId" runat="server" AppendDataBoundItems="true" >
<asp:ListItem>Select a product</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Product Main Image" FooterText="Product Main Image" HeaderText="Product Main Image">
<ItemTemplate>
<asp:Label ID="lblMainImgId" runat="server" Text='<%# Eval("ImageId") %>' ></asp:Label>
<asp:Label ID="lblMainImgName" runat="server" Text='<%# Eval("ImageName") %>' ></asp:Label> <br />
<asp:Image ID="imgMain" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="flupEditMain" runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupMain" runat="server" AllowMultiple="false" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Supporting Images" FooterText="Supporting Images" HeaderText="Supporting Images">
<ItemTemplate>
<asp:GridView ID="grdSupImages"
runat="server" ShowHeader="false" CellPadding="4"
ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"
OnRowEditing="grdSupImages_RowEditing"
OnRowUpdating="grdSupImages_RowUpdating" AllowPaging="true" PageSize="4"
OnPageIndexChanging="grdSupImages_PageIndexChanging" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="imgSupId" runat="server" Text='<%# Eval("ImgId") %>' ></asp:Label>
<asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:Label ID="imgSupName" runat="server" Text='<%# Eval("ImageName") %>' AssociatedControlID="imgSup"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:CheckBox ID="chkSupImages" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupExtra" runat="server" AllowMultiple="true" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<br />
<span onclick="return confirm('Are you sure you want to delete these images?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<br />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
My code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.IO;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class Admin_ProductManagement_addProdImage : System.Web.UI.Page
{
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
private string imageDirectory;
protected void Page_Load(object sender, EventArgs e)
{
// ensure images are uploaded to the right folder.
imageDirectory = Path.Combine(
Request.PhysicalApplicationPath, #"Images\ProductImages");
if (!this.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
// define ado.net objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "DisplayMain";
try
{
con.Open(); // try to open the connection
DataSet ds = new DataSet(); // Initializes a new instance of the DataSet class
adapter.Fill(ds, "ProductImages"); // Adds or refreshes rows in the DataSet to match those in the data source using the DataSet and DataTable names
grdImages.DataSource = ds; // sets the gridview datasource
grdImages.DataBind(); // binds data to gridview
// find dropdownlist in the footer row of the gridview
DropDownList prods = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId");
// call function
lstProducts(prods);
}
catch (Exception err)
{
lblGrdImages.Text = "BindGrid error: " + err.Message + err.Source + err.StackTrace; // display exceptions in label
}
finally
{
con.Close(); // close connection, even if action was unsuccessful.
}
}
protected void BindNestedGrid(int product, GridView grd)
{
// define ado.net objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "DisplayExtra";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = product;
// try to connect, fill dataset and close connection. Also catch exceptions.
try
{
con.Open(); // open the connection.
DataSet rds = new DataSet(); // initialize a data set.
adapt.Fill(rds, "ExtraImages"); // fills dataset
grd.DataSource = rds; // assign data source.
grd.DataBind(); // bind data.
}
catch (Exception err)
{
lblGrdImages.Text = "Bind Nested Grid Error: " + err.Message; // catch exceptions.
}
finally
{
con.Close(); // close the db connection
}
}
protected void lstProducts(DropDownList prods)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader;
// define the sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "LstProds";
try
{
con.Open(); // try to connect to db.
reader = cmd.ExecuteReader(); // execut the reader
while (reader.Read())
{
ListItem item = new ListItem(); // create listitem
item.Text = reader["ProductName"].ToString(); // add product name to item text
item.Value = reader["ProductId"].ToString(); // add productId to item value
prods.Items.Add(item); // populate dropdown list.
}
}
catch (Exception err)
{
lblGrdImages.Text = "List Products Error: " + err.Message; // display error message in a label
}
finally
{
con.Close(); // close the connection.
}
}
protected void addMain(int ProdId, string ImgName, string ImgPath)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "AddMain";
cmd.Parameters.Add(new SqlParameter("#ImageName", SqlDbType.VarChar, 50));
cmd.Parameters["#ImageName"].Value = ImgName;
cmd.Parameters.Add(new SqlParameter("#ImagePath", SqlDbType.VarChar, -1));
cmd.Parameters["#ImagePath"].Value = ImgPath;
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = ProdId;
try
{
con.Open(); // attempt to open the connection
DataSet ds = new DataSet(); // initialize the dataset
adapter.Fill(ds, "ProductImages"); // fill the data set.
}
catch (Exception err)
{
lblGrdImages.Text = "Add main error: " + err.Message; // display exceptions in a label control
}
finally
{
con.Close(); // close connection.
}
}
protected void addExtraImages(int ProductId, string ExImgName, string ExImagePath)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "AddExtra";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = ProductId;
cmd.Parameters.Add(new SqlParameter("#ImageName", SqlDbType.VarChar,50));
cmd.Parameters["#ImageName"].Value = ExImgName;
cmd.Parameters.Add(new SqlParameter("#ImagePath", SqlDbType.VarChar,-1));
cmd.Parameters["#ImagePath"].Value = ExImagePath;
try
{
con.Open(); // try to open db connection
DataSet ds = new DataSet(); // initialize data set.
adapter.Fill(ds, "ProductImages"); // fill the data set.
}
catch (Exception err)
{
lblGrdImages.Text = "Add extra images error: " + err.Message; // display exception in a label
}
finally
{
con.Close(); // close the connection
}
}
protected void DeleteProductImages(int Product)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "Delete";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = Product;
try
{
con.Open(); // open connection
DataSet ds = new DataSet(); // initialize rthe dataset
adapter.Fill(ds); // fill dataset.
}
catch (Exception err)
{
lblGrdImages.Text = "Delete error: " + err.Message; // report error in a label.
}
finally
{
con.Close(); // close the connection.
}
}
protected void grdImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdImages.PageIndex = e.NewPageIndex; // sets the page index
BindGrid(); // bind the grid.
}
protected void grdImages_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdImages.EditIndex = -1; // sets the page index
BindGrid(); // bind the grid.
}
private bool isValid(HttpPostedFile file, string[] extAry, string ext) // checks extension
{
bool isValid = false;
for (int i = 0; i < extAry.Length; i++)
{
if (ext.ToLowerInvariant().IndexOf(extAry[i]) > -1)
isValid = true;
}
return isValid;
}
protected void uploadMainImage() {
string[] validFileTypes = { ".jpg", ".png" }; // file type array
FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain"); // find control
DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId"); // find control
string mainFile = Path.GetFileName(main.PostedFile.FileName); // get file name.
string ext = Path.GetExtension(mainFile); // get file extension.
if (isValid(main.PostedFile, validFileTypes, ext)) // check if file extension is valid.
{
if (File.Exists(mainFile)) // check if file exists
{
lblGrdImages.Text = "File with the name: " + mainFile + " already exists. Please rename or choose a different file.";
}
else
{
try
{
string serverFileName = Path.GetFileName(mainFile); // assign values to variables
string uploadPath = Path.Combine(imageDirectory, serverFileName);
int Product = Convert.ToInt32(products.SelectedValue);
main.SaveAs(uploadPath); // save file
addMain(Product, serverFileName, #"~\Images\ProductImages\" + serverFileName); // Call stored procedure
}
catch (Exception err)
{
lblGrdImages.Text = err.Message;
}
}
}
}
protected void uploadExtraImages()
{
string[] validFileTypes = { ".jpg", ".png" }; // file type array
FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra"); // find conrol
DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId"); // find control
if (extra.HasFiles)
{
foreach (HttpPostedFile file in extra.PostedFiles)
{
string ext = Path.GetExtension(file.FileName);
if (isValid(file, validFileTypes, ext)) // check file extension
{
string serverFileName = Path.GetFileName(file.FileName); // assign values to variables
string uploadPath = Path.Combine(imageDirectory, serverFileName);
int Product = Convert.ToInt32(products.SelectedValue);
try
{
file.SaveAs(uploadPath); // save file
addExtraImages(Product, serverFileName, #"~\Images\ProductImages\" + serverFileName); // call stored procedure
}
catch (Exception err)
{
lblGrdImages.Text = "Error: " + err.Message;
}
}
}
}
}
protected void grdImages_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
// find the required controls in the grdview.
FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain");
FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra");
if (main.HasFile)
{
uploadMainImage();
if (extra.HasFiles)
{
uploadExtraImages();
}
grdImages.EditIndex = -1;
BindGrid();
}
else
{
lblGrdImages.Text = "Product main image is required.";
}
}
}
protected void grdImages_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (!this.IsPostBack)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView grd = (GridView)e.Row.FindControl("grdSupImages"); // find controls
Label prodId = (Label)e.Row.FindControl("lblProdId");
int product = Convert.ToInt32(prodId.Text); // assign values to variables.
BindNestedGrid(product, grd); // call the function.
}
}
}
protected void grdImages_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// find controls
Label product = (Label)grdImages.Rows[e.RowIndex].FindControl("lblProdId");
Label image = (Label)grdImages.Rows[e.RowIndex].FindControl("lblMainImgName");
GridView grd = (GridView)grdImages.Rows[e.RowIndex].FindControl("grdSupImages");
// declare variables and assign values
int prodid = Convert.ToInt32(product.Text);
string path = Server.MapPath(#"~\Images\ProductImages\" + image.Text);
File.Delete(path);
foreach(GridViewRow row in grd.Rows)
{
Label img = (Label)row.FindControl("imgSupName");
string imgName = img.Text;
string imgPath = Server.MapPath(#"~\Images\ProductImages\" + imgName);
try
{
File.Delete(imgPath);
}
catch (Exception err)
{
lblGrdImages.Text = "File Delete Error: " + err.Message + "<br />" + err.InnerException + "||" + err.StackTrace;
}
}
DeleteProductImages(prodid);
grdImages.EditIndex = -1;
BindGrid();
}
protected void grdImages_RowEditing(object sender, GridViewEditEventArgs e)
{
grdImages.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void grdImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void grdSupImages_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void grdSupImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
}
}
I would be eternally grateful of any assistance with this matter. If you require any further information please let me know and I will provide.
Although nobody wanted to help me, I have found the answer to my problem.
I thought id share this information as it may be able to help somebody else.
This is what I came up with for my child gridview pageindexchanging event:
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
BindNestedGrid(Convert.ToInt32(gv.ToolTip), gv);
}
here i want to have no.of coloumns i have checked and deleted in lable
i have used following code to execute my query of deleting multiple values in gridview using checkbox
here is my code and script part
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
grd_bnd();
}
}
private void grd_bnd()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from student", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void Button3_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox1 = (CheckBox)row.FindControl("checkboxdelete");
if (checkbox1.Checked)
{
int rollno = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString());
//CheckBox checkbox1 = (CheckBox)row.FindControl("checkbox1");
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("delete from student where rollno = #rollno ", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#rollno", SqlDbType.Int).Value = rollno.ToString();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
}
}
grd_bnd();
}
}
and here is script
<asp:GridView ID="GridView1" runat="server" DataKeyNames="rollno" AllowSorting="true" AutoGenerateColumns="False" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" >
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="checkboxdelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblname" runat ="server" Text='<%#Eval("name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Roll No.">
<ItemTemplate>
<asp:Label ID="lblrollno" runat ="server" Text='<%#Eval("rollno") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Batch">
<ItemTemplate>
<asp:Label ID="lblbatch" runat ="server" Text='<%#Eval("batch") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Course">
<ItemTemplate>
<asp:Label ID="lblcourse" runat ="server" Text='<%#Eval("course") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</gridview>
<asp:Button ID="Button3" runat="server" Font-Bold="True" Text="Delete Selected" ForeColor="#000066" OnClick="Button3_Click" />
<asp:Label ID="Label1" runat="server" ForeColor="#666666"></asp:Label>
i wanna get the number of entities deleted in above lable , lable1.
Simply add a count before your loop
protected void Button3_Click(object sender, EventArgs e)
{
int rows = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox1 = (CheckBox)row.FindControl("checkboxdelete");
if (checkbox1.Checked)
{
int rollno = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString());
//CheckBox checkbox1 = (CheckBox)row.FindControl("checkbox1");
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("delete from student where rollno = #rollno ", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#rollno", SqlDbType.Int).Value = rollno.ToString();
con.Open();
rows += cmd.ExecuteNonQuery(); //Can return 0 if no rows were deleted!
con.Close();
cmd.Dispose();
}
}
grd_bnd();
MessageBox.Show(String.Format("Rows affected {0}", rows);
}
You can use the return value of ExecuteNonQuery:
int numDeleted = cmd.ExecuteNonQuery();
MSDN: returns the number of rows affected.
If you want the total rows use a variable:
int totalNumDeleted = 0;
foreach (GridViewRow row in GridView1.Rows)
{
// ...
int numDeleted = cmd.ExecuteNonQuery();
totalNumDeleted += numDeleted;
}
Label1.Text = string.Format("{0} students were deleted successfully.", totalNumDeleted);
I have a ckeck box field in grid view header.On checking this Check box all the check boxes
in grid view gets checked. Now i want to delete all the rows on button click.
Code for the check box in my aspx page is as follows:
<HeaderTemplate>
Select All: <asp:CheckBox ID="chkboxSelectAll" AutoPostBack="true" OnCheckedChanged="chkboxSelectAll_CheckedChanged"
runat="server"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkEmp" runat="server"></asp:CheckBox>
</ItemTemplate></asp:TemplateField>
In my code behind i have tried this but its not working:
also In my Grid view DataKeyNames="id" and bindgrid() method is working fine.
For selecting all rows:
protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox ChkBoxHeader = (CheckBox)Grd.HeaderRow.FindControl("chkboxSelectAll");
foreach (GridViewRow row in Grd.Rows)
{
CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkEmp");
if (ChkBoxHeader.Checked == true)
{
ChkBoxRows.Checked = true;
}
}
For deleting all selected rows
protected void btn_click(object sender, EventArgs e)
{
CheckBox ChkBoxHeader = (CheckBox)Grd.HeaderRow.FindControl("chkboxSelectAll");
foreach (GridViewRow row in Grd.Rows)
{
// Only look in data rows, ignore header and footer rows
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkEmp");
if (ChkBoxHeader.Checked == true)
{
ChkBoxRows.Checked = true;
var id = Grd.DataKeys[row.RowIndex].Value;
SqlConnection con = new SqlConnection(constr);
string qry = "delete from empdetail where id=#id";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#id", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
bindgrid();
}
}
}
}
Please Help me. Error i got is "Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
Your first problem is that you are searching for the chkEmp check box, but it does not exist in the header row, because foreach (GridViewRow row in Grd.Rows) will loop through all rows in the grid (including header, data and footer rows).
The ItemTemplate in your grid view markup applies to rows of type DataRow, so you need to restrict your searching for chkEmp to just data rows, like this:
protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox ChkBoxHeader = (CheckBox)Grd.HeaderRow.FindControl("chkboxSelectAll");
foreach (GridViewRow row in Grd.Rows)
{
// Only look in data rows, ignore header and footer rows
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkEmp");
if (ChkBoxHeader.Checked == true)
{
ChkBoxRows.Checked = true;
var id = Grd.DataKeys[row.RowIndex].Value;
SqlConnection con = new SqlConnection(constr);
string qry = "delete from empdetail where id=#id";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#id", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
bindgrid();
}
else
{
ChkBoxRows.Checked = false;
}
}
}
}
<asp:GridView ID="GrdAtt" runat="server" CssClass="table table-small-font table-bordered table-striped" Font-Size="Small" EmptyDataRowStyle-ForeColor="#cc0000" HeaderStyle-Font-Size="10" HeaderStyle-Font-Names="Arial" HeaderStyle-Font-Italic="true"
AutoGenerateColumns="False" EmptyDataText="No Data Found" OnRowDataBound="GrdEmplistFromAtt_RowDataBound"
HeaderStyle-ForeColor="#990000">
<Columns>
<asp:TemplateField HeaderText=" " HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
ItemStyle-Width="25px">
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" AutoPostBack="true" OnCheckedChanged="chkAll_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSingle" runat="server" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" Width="10px"></ItemStyle>
</asp:TemplateField>
</Columns>
<HeaderStyle HorizontalAlign="Justify" VerticalAlign="Top"
Font-Bold="true" />
<RowStyle Font-Size="Small" Height="1" Font-Italic="true" />
</asp:GridView>
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk_All = (CheckBox)GrdAtt.HeaderRow.FindControl("chkAll");
if (chk_All.Checked == true)
{
foreach (GridViewRow gvr in GrdEmplistFromAtt.Rows)
{
CheckBox chk_Single = (CheckBox)gvr.FindControl("chkSingle");
if (chk_Single.Visible == true)
{
chk_Single.Checked = true;
lblSelectedRecord.InnerText = (Convert.ToInt32(lblSelectedRecord.InnerText) + 1).ToString();
}
}
}
else
{
foreach (GridViewRow gvr in GrdEmplistFromAtt.Rows)
{
CheckBox chk_Single = (CheckBox)gvr.FindControl("chkSingle");
chk_Single.Checked = false;
lblSelectedRecord.InnerText = "0";
}
}
}