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";
}
}
}
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 want to bind only Table Columns to CheckBoxList and then the selected columns should be displayed in a GridView.
My code so far is:
public void BindCheckBoxList(DataSet ds)
{
int i = 0;
foreach (DataColumn dc in ds.Tables[0].Columns)
{
ListItem li = new ListItem(dc.ToString(), i.ToString());
CheckBoxList1.Items.Add(li); i++;
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="HobbyId">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%# Eval("IsSelected") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Hobby" HeaderText="Hobby" ItemStyle-Width="150px" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />
in aspx.cs code
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [HobbyId], [Hobby], [IsSelected] FROM Hobbies"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void mainGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate))
{
if (e.Row.Cells[1].FindControl("selectCheckbox") == null)
{
CheckBox selectCheckbox = new CheckBox();
//Give id to check box whatever you like to
selectCheckbox.ID = "newSelectCheckbox";
e.Row.Cells[1].Controls.Add(selectCheckbox);
}
}
}
i think you use this code.
Here a complete example to hide GridView Columns based on a CheckBoxList.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//fill the datatable from the database
DataTable dt = //fill the table here...
//bind the table to the grid
GridView1.DataSource = dt;
GridView1.DataBind();
//loop all the datatable columns to fill the checkboxlist
for (int i = 0; i < dt.Columns.Count; i++)
{
CheckBoxList1.Items.Insert(i, new ListItem(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName, true));
}
}
}
protected void CheckBoxList1_TextChanged(object sender, EventArgs e)
{
//loop all checkboxlist items
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected == true)
{
//loop all the gridview columns
for (int i = 0; i < GridView1.Columns.Count; i++)
{
//check if the names match and hide the column
if (GridView1.HeaderRow.Cells[i].Text == item.Value)
{
GridView1.Columns[i].Visible = false;
}
}
}
}
}
And on the .aspx page
<asp:CheckBoxList ID="CheckBoxList1" runat="server" OnTextChanged="CheckBoxList1_TextChanged" AutoPostBack="true"></asp:CheckBoxList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="field01" HeaderText="Column A" />
<asp:BoundField DataField="field02" HeaderText="Column B" />
<asp:BoundField DataField="field03" HeaderText="Column C" />
<asp:BoundField DataField="field04" HeaderText="Column D" />
<asp:BoundField DataField="field05" HeaderText="Column E" />
</Columns>
</asp:GridView>
Note that AutoGenerateColumns is set to false. If they are auto-generated the columns are not part of the GridView Columns Collection.
And of course HeaderText="xxx" must match the column names from the database that are stored in the DataTable.
What i'm trying to do is execute some code when a checkbox in a gridview is checked, with the code being executed row by row. I debugged the code and every time returns false despite the checkboxes being checked. The code i'm trying to execute works if the conditional statement is removed.
protected void ShoppingCartButton_Click(object sender, EventArgs e)
{
Label1.Text = "HIH0HI";
OleDbConnection myconn = new OleDbConnection();
myconn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|ProjectDatabase.accdb";
string UserID = Session["UserID"].ToString();
StringBuilder sb3 = new StringBuilder();
foreach (GridViewRow row in GridView1.Rows)
{
string unpredictable = "";
bool hi = true;
unpredictable = row.Cells[1].Text;
CheckBox chk = row.Cells[0].Controls[1] as CheckBox;
hi = chk.Checked;
sb3.Append(hi.ToString());
if (hi==true)
{
string command1 = "insert into Cart ([Username],[GameID]) values (#Username, #GameID)";
OleDbCommand cmd = new OleDbCommand(command1, myconn);
cmd.Parameters.AddWithValue("#Username", UserID);
cmd.Parameters.AddWithValue("#GameID", unpredictable);
myconn.Open();
cmd.ExecuteNonQuery();
myconn.Close();
}
}
Label1.Text = sb3.ToString();
}
Markup for the button and the gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" EmptyDataText ="Data Entry Error">
<Columns>
<asp:TemplateField HeaderText ="Add to Cart?">
<ItemTemplate>
<asp:CheckBox ID="checkbx" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button runat="server" id="ShoppingCartButton" Text="Add to shopping cart" OnClick="ShoppingCartButton_Click" />
This was a simple one. Have to enclose any data binding logic in
if (!IsPostBack)
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).
when i checked [checked box] data on my page (1) and then go on to next page (2) through paging(bottom button of pages like [1234]) and then checked data on page (2).
when i came back to page (1) then it remain unchecked as i don't checked anything!!!
all the things remains at its original positions. all are unchecked on both pages .
when coming from 1 page to page 2 (check-boxes of page 1 forget his value and get unchecked) and after when coming from page 2 to page 1 same thing happens.
sorry for my bad and rough English.
any suggestion??
If its a gridview or any repeater control try this
Gridview HTML
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" AllowPaging="True"
PageSize="5" Width="324px" DataKeyNames="CategoryID"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS Codes
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
RememberOldValues();
GridView1.PageIndex = e.NewPageIndex;
BindData();
RePopulateValues();
}
And
private void RememberOldValues()
{
ArrayList categoryIDList = new ArrayList();
int index = -1;
foreach (GridViewRow row in GridView1.Rows)
{
index = (int) GridView1.DataKeys[row.RowIndex].Value;
bool result = ((CheckBox)row.FindControl("CheckBox1")).Checked;
// Check in the Session
if (Session[CHECKED_ITEMS] != null)
categoryIDList = (ArrayList)Session[CHECKED_ITEMS];
if (result)
{
if (!categoryIDList.Contains(index))
categoryIDList.Add(index);
}
else
categoryIDList.Remove(index);
}
if (categoryIDList != null && categoryIDList.Count > 0)
Session[CHECKED_ITEMS] = categoryIDList;
}
And
private void RePopulateValues()
{
ArrayList categoryIDList = (ArrayList)Session[CHECKED_ITEMS];
if (categoryIDList != null && categoryIDList.Count > 0)
{
foreach (GridViewRow row in GridView1.Rows)
{
int index = (int)GridView1.DataKeys[row.RowIndex].Value;
if (categoryIDList.Contains(index))
{
CheckBox myCheckBox = (CheckBox) row.FindControl("CheckBox1");
myCheckBox.Checked = true;
}
}
}
}
Bind Data Code
EDIT
/* QUERY */
private const string QUERY_SELECT_ALL_CATEGORIES = "SELECT * FROM Categories";
private void BindData()
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(QUERY_SELECT_ALL_CATEGORIES,
myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
GridView1.DataSource = ds;
GridView1.DataBind();
}
For more details chk this Maintaining_State_of_CheckBoxes
When you are navigating from one page to another ,your page refreshes so it cant retain value for checkbox,If you want to do this you have to do it from code behind ,write code
Checkbox.Checked=True in !IsPostback according to your valid conditions.