Why doesn't radio button work? - c#

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;
}
}
}
}

Related

Binding GridView Columns to CheckBoxList Dynamically in C#

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.

how to enable selected row in gridview in asp .net and c#

Here is my aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1"
OnRowCommand="GridView1_RowCommand" AutoGenerateSelectButton="True" EnablePersistedSelection="True">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class" />
<asp:BoundField DataField="Section" HeaderText="Section"
SortExpression="Section" />
<asp:BoundField DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button runat="server" ID="btnedit" Text="Edit" CommandName="EditRow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Container.DataItemIndex %>' CommandName="Deleterow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is code behind:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
GridViewRow gr = GridView1.SelectedRow;
gr.Cells[1].Text = Textusername.Text;
gr.Cells[2].Text = Textclass.Text;
gr.Cells[3].Text = Textsection.Text;
gr.Cells[4].Text = Textaddress.Text;
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
}
The selected row did not select in gridview. May i know how to enable gridview row. I used msdn and other documents and i followed,but nothing helps.
I design i set enable selection, but still i didn't find out issue.
Can anyone help me?
Thanks,
Basically we get SelectedRow of GridView Upon some GridviewRow Action event like OnSelectedIndexChanged , OnSelectedIndexChanging , OnRowEditing or from Template control like Button click. But here in your coding I don't think your btnsub_Click is inside Gridview so If you want to use the SelectedGridViewRow after your GridviewRow Action event then save the index in some temporary variable or pass the variable to method as argument.
protected void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
{
int index = Gridview1.SelectedIndex;
hiddenfield.Value = index.ToString();
}
OR In OnRowEditing also you can get the index of row
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditRow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
int index = gr.RowIndex;
hidval.Value = index.ToString();
}
}
and on button Click you can get the hiddenfield value as index:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
if(!String.IsNullOrEmpty(hiddenfield.Value))
{
int index = Convert.ToInt16(hiddenfield.Value);
GridView1.Rows[index].Cells[1].Text = Textusername.Text;
GridView1.Rows[index].Cells[2].Text = Textclass.Text;
GridView1.Rows[index].Cells[3].Text = Textsection.Text;
GridView1.Rows[index].Cells[4].Text = Textaddress.Text;
}
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
}

How to Keep row values in gridview after adding new row?

I have a gridview with textboxes for item no, desc qty, cost, extncost. When itemno entered in the textbox desc and cost of the item will comes automatically by on textbox event change.
Here when i add a new row in the grid view, values of last entered value got disappears.
when i am checking using break point i can able to see the last entered values in data table.
Since, while adding new row has blank text boxes, now system considers blank text box for on text change event. So, last entered values also not displaying. Text box changes in one row also affects in other rows.
Here is the ASPX.page code:
<asp:UpdatePanel ID="gin_pnlupdt" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:GridView ID="grv_gindet" runat="server" ShowFooter="True" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="grvStudentDetails_RowDeleting"
OnRowDataBound="grv_gindtrowcmd" OnRowCommand="grv_gindetrowcmd">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="SNo" />
<asp:TemplateField HeaderText="Item Number">
<ItemTemplate>
<asp:TextBox ID="txt_itemno" runat="server" OnTextChanged="txt_itemno_changed" AutoPostBack="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Description">
<ItemTemplate>
<asp:Label ID="txt_itemdesc" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txt_qty" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit Cost">
<ItemTemplate>
<asp:Label ID="txt_ucost" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Extended Cost">
<ItemTemplate>
<asp:Label ID="txt_extncost" runat="server"></asp:Label>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="BtnAddRow" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="grv_gindet" />
</Triggers>
</asp:UpdatePanel>
Here is the CS code for add new row:
protected void AddNewRow()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox TextBoxItem =
(TextBox)grv_gindet.Rows[rowIndex].Cells[1].FindControl("txt_itemno");
Label TextBoxDesc =
(Label)grv_gindet.Rows[rowIndex].Cells[2].FindControl("txt_itemdesc");
TextBox TextBoxQty =
(TextBox)grv_gindet.Rows[rowIndex].Cells[3].FindControl("txt_qty");
Label TextBoxucost =
(Label)grv_gindet.Rows[rowIndex].Cells[4].FindControl("txt_ucost");
Label TextBoxextncost =
(Label)grv_gindet.Rows[rowIndex].Cells[5].FindControl("txt_extncost");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxItem.Text;
dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxDesc.Text;
dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxQty.Text;
dtCurrentTable.Rows[i - 1]["Col4"] = TextBoxucost.Text;
dtCurrentTable.Rows[i - 1]["Col5"] = TextBoxextncost.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
grv_gindet.DataSource = dtCurrentTable;
grv_gindet.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
Code for retrive Previous data:
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox TextBoxItem = (TextBox)grv_gindet.Rows[rowIndex].Cells[1].FindControl("txt_itemno");
Label TextBoxDesc = (Label)grv_gindet.Rows[rowIndex].Cells[2].FindControl("txt_itemdesc");
TextBox TextBoxQty =
(TextBox)grv_gindet.Rows[rowIndex].Cells[3].FindControl("txt_qty");
Label TextBoxucost =
(Label)grv_gindet.Rows[rowIndex].Cells[4].FindControl("txt_ucost");
Label TextBoxextncost =
(Label)grv_gindet.Rows[rowIndex].Cells[5].FindControl("txt_extncost");
TextBoxItem.Text = dt.Rows[i]["Col1"].ToString();
TextBoxDesc.Text = dt.Rows[i]["Col2"].ToString();
TextBoxQty.Text = dt.Rows[i]["Col3"].ToString();
TextBoxucost.Text = dt.Rows[i]["Col4"].ToString();
TextBoxextncost.Text = dt.Rows[i]["Col5"].ToString();
rowIndex++;
}
}
}
}
Textbox change event:
protected void txt_itemno_changed(object sender, EventArgs e)
{
//TextBox thisTextBox = (TextBox)sender;
//GridViewRow thisGridViewRow = (GridViewRow)thisTextBox.Parent.Parent;
//int row = thisGridViewRow.RowIndex;
GridViewRow currentrow = (GridViewRow)((TextBox)sender).Parent.Parent;
TextBox thisTextBox = (TextBox)currentrow.FindControl("txt_itemno");
int row = currentrow.RowIndex;
//rowChanged[row] = true;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AWCC"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ITEMDET.ITEMDESC,RGITEMDET.UNITCOST FROM ITEMDET JOIN RGITEMDET ON RGITEMDET.ITEMNO=ITEMDET.ITEMNO WHERE ITEMDET.ITEMNO ='" + thisTextBox.Text + "' ", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
grv_gindet.Rows[row].Cells[2].Text = dr["ITEMDESC"].ToString();
grv_gindet.Rows[row].Cells[4].Text = dr["UNITCOST"].ToString();
}
}
thisTextBox.Enabled = false;
}
Postback control code for gridview child element:
protected void grv_gindtrowcmd(object sender, GridViewRowEventArgs e)
{
try
{
TextBox txtitm = e.Row.FindControl("txt_itemno") as TextBox;
LinkButton lnkbtn = e.Row.FindControl("ShowDeleteButton") as LinkButton;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(txtitm);
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(lnkbtn);
}
catch
{
}
}
protected void grv_gindetrowcmd(object sender, GridViewCommandEventArgs e)
{
try
{
Button btnad = grv_gindet.FooterRow.FindControl("ButtonAdd") as Button;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(btnad);
}
catch
{
}
}
Kinldy provide a solution ASAP, do the needful.
I hope this will help you, change this in Textchange event
GridViewRow currentrow = (GridViewRow)((TextBox)sender).Parent.Parent.Parent.Parent;
TextBox thisTextBox = (TextBox)currentrow.FindControl("txt_itemno");
if (!string.IsNullOrWhiteSpace(thisTextBox.Text))
{
int row = currentrow.RowIndex;
//rowChanged[row] = true;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AWCC"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ITEMDET.ITEMDESC,RGITEMDET.UNITCOST FROM ITEMDET JOIN RGITEMDET ON RGITEMDET.ITEMNO=ITEMDET.ITEMNO WHERE ITEMDET.ITEMNO ='" + thisTextBox.Text + "' ", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
((Label)(grv_gindet.Rows[row].FindControl("txt_itemdesc"))).Text = dr["ITEMDESC"].ToString();
((TextBox)(grv_gindet.Rows[row].FindControl("txt_ucost"))).Text = dr["UNITCOST"].ToString();
}
con.Close();
}
thisTextBox.Enabled = false;
}

Insert the data when user click on select button inside the gridview

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).

edit row in gridview

I would like to help me with my code. I have 2 gridviews. In the first gridview the user can choose with a checkbox every row he wants. These rows are transfered in the second gridview. All these my code does them well.Now, I want to edit the quantity column in second gridview to change the value but i don't know what i must write in edit box.
Here is my code:
using System;
using System.Data;
using System.Data.SqlClient;
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.Collections;
public partial class ShowLand : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindPrimaryGrid();
BindSecondaryGrid();
}
}
private void BindPrimaryGrid()
{
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string query = "select * from Land";
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
sda.Fill(dt);
gridview2.DataSource = dt;
gridview2.DataBind();
}
private void GetData()
{
DataTable dt;
if (ViewState["SelectedRecords1"] != null)
dt = (DataTable)ViewState["SelectedRecords1"];
else
dt = CreateDataTable();
CheckBox chkAll = (CheckBox)gridview2.HeaderRow
.Cells[0].FindControl("chkAll");
for (int i = 0; i < gridview2.Rows.Count; i++)
{
if (chkAll.Checked)
{
dt = AddRow(gridview2.Rows[i], dt);
}
else
{
CheckBox chk = (CheckBox)gridview2.Rows[i]
.Cells[0].FindControl("chk");
if (chk.Checked)
{
dt = AddRow(gridview2.Rows[i], dt);
}
else
{
dt = RemoveRow(gridview2.Rows[i], dt);
}
}
}
ViewState["SelectedRecords1"] = dt;
}
private void SetData()
{
CheckBox chkAll = (CheckBox)gridview2.HeaderRow.Cells[0].FindControl("chkAll");
chkAll.Checked = true;
if (ViewState["SelectedRecords1"] != null)
{
DataTable dt = (DataTable)ViewState["SelectedRecords1"];
for (int i = 0; i < gridview2.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gridview2.Rows[i].Cells[0].FindControl("chk");
if (chk != null)
{
DataRow[] dr = dt.Select("id = '" + gridview2.Rows[i].Cells[1].Text + "'");
chk.Checked = dr.Length > 0;
if (!chk.Checked)
{
chkAll.Checked = false;
}
}
}
}
}
private DataTable CreateDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("name");
dt.Columns.Add("price");
dt.Columns.Add("quantity");
dt.Columns.Add("total");
dt.AcceptChanges();
return dt;
}
private DataTable AddRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["id"] = gvRow.Cells[1].Text;
dt.Rows[dt.Rows.Count - 1]["name"] = gvRow.Cells[2].Text;
dt.Rows[dt.Rows.Count - 1]["price"] = gvRow.Cells[3].Text;
dt.Rows[dt.Rows.Count - 1]["quantity"] = gvRow.Cells[4].Text;
dt.Rows[dt.Rows.Count - 1]["total"] = gvRow.Cells[5].Text;
dt.AcceptChanges();
}
return dt;
}
private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'");
if (dr.Length > 0)
{
dt.Rows.Remove(dr[0]);
dt.AcceptChanges();
}
return dt;
}
protected void CheckBox_CheckChanged(object sender, EventArgs e)
{
GetData();
SetData();
BindSecondaryGrid();
}
private void BindSecondaryGrid()
{
DataTable dt = (DataTable)ViewState["SelectedRecords1"];
gridview3.DataSource = dt;
gridview3.DataBind();
}
}
and the source code is
<asp:GridView ID="gridview2" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="SqlDataSource5">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" onclick = "checkAll(this);"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" onclick = "Check_Click(this)"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False"
ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="name" HeaderText="name"
SortExpression="name" />
<asp:BoundField DataField="price" HeaderText="price" SortExpression="price" />
<asp:BoundField DataField="quantity" HeaderText="quantity"
SortExpression="quantity" />
<asp:BoundField DataField="total" HeaderText="total" SortExpression="total" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Land]"></asp:SqlDataSource>
<br />
</div>
<div>
<asp:GridView ID="gridview3" runat="server"
AutoGenerateColumns = "False" DataKeyNames="id"
EmptyDataText = "No Records Selected" >
<Columns>
<asp:BoundField DataField = "id" HeaderText = "id" />
<asp:BoundField DataField = "name" HeaderText = "name" ReadOnly="True" />
<asp:BoundField DataField = "price" HeaderText = "price"
DataFormatString="{0:c}" ReadOnly="True" />
<asp:TemplateField HeaderText="quantity">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("quantity")%>'</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("quantity") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField = "total" HeaderText = "total"
DataFormatString="{0:c}" ReadOnly="True" />
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
<asp:Label ID="totalLabel" runat="server"></asp:Label>
<br />
</div>
</form>
</body>
</html>
This is not particular asp.net solution but that's how I do something like this in my Windows app.
First of all you shoul make shure that there's a selected row in your GridView (gridView.SelectedRow != null). DataTable object allows you to get access to desired row by accessing it not by numeric index but by DataRow-type object index. After getting a reference to the row which fields' value you want to modify just go ahead with changes.
Here's the example:
if (gridView.SelectedRow != null)
{
dataTable.Rows[gridView.SelectedRow].BeginEdit();
dataTable.Rows[gridView.SelectedRow]["yourFieldName"] = newValue;
dataTable.Rows[gridView.SelectedRow].EndEdit();
gridView.DataSource = dataTable;
}
Hope my answer is of any help because I've never dealt with asp.net before.

Categories