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)
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 need to create a webpage containing a grid view with combo box. condition is:- the combo box value should be inserted on my SQL db and update the db/grid view when i click save button.[i added the image of proposed design of the page]any help with the code is so much appreciated! thank you!
GridView Markup
Below I have a simple GridView ASP.Net GridView control populated from the Customers table of Northwind database. It displays 2 columns Contact Name and City of which city is editable via ASP.Net DropDownList control. The identifier column Customer Id is bind to the DataKeyNames property.
<asp:GridView ID="gvCustomers" DataKeyNames = "CustomerId" runat="server" AutoGenerateColumns = "false" OnRowEditing = "EditCustomer" OnRowDataBound = "RowDataBound" OnRowUpdating = "UpdateCustomer" OnRowCancelingEdit = "CancelEdit">
<Columns>
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name" />
<asp:TemplateField HeaderText = "City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>' Visible = "false"></asp:Label>
<asp:DropDownList ID = "ddlCities" runat = "server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
Binding the GridView
Below is the code to Bind the GridView control with data.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "SELECT top 10 * FROM Customers";
SqlCommand cmd = new SqlCommand(query);
gvCustomers.DataSource = GetData(cmd);
gvCustomers.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
Editing the GridView Row
The below events handle the GridView Row Edit and Cancel Edit Events
C#
protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvCustomers.EditIndex = -1;
BindData();
}
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";
}
}
}
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).