selected row in gridview - c#

I have two table in sql server as follow
PatientDetail - 1st table name
PatientId --- primary key
firstname
lastname
Patexam - 2nd table name
PId ---- foreign key of first table PatientId
Exam
I have one gridview in the page which shows all the column of first table as below
<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<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>
I have one button with the text value = "formatric3d"
Now when i select one row in gridview and then click on button with
value = "formatric3d",
so on click event I want to insert the selected row patientid as well as button text value = "formatric3d" into the table name Patexam.
That means PId equal to PatientId which is selected on gridview and Exam equal to button text value = "formatric3d".

Is this something you want?
<asp:Button runat="server" ID="btnExam" Text="formatric3d" OnClick="Exam_ClickHandler" />
<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chk" />
<asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" />
<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>
<h3>Patient Exams</h3>
<asp:DataList runat="server" ID="dtlExams">
<ItemTemplate>
<%#Eval("Exam") %>
</ItemTemplate>
</asp:DataList>
//////////////// tree view
<asp:TreeView runat="server" ID="tvExams">
</asp:TreeView>
On code behind page:
protected void Exam_ClickHandler(object sender, EventArgs e)
{
foreach (GridViewRow row in gvDoctorList.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("chk");
if (chk.Checked)
{
string patientId = ((Label)row.FindControl("lblPID")).Text;
string exam = ((Button)sender).Text;
///your insertion query goes here.
///
GetPatientExams(patientId);
}
}
}
protected void Patient_ExamHandler(object sender, CommandEventArgs e)
{
string patientId = e.CommandArgument.ToString();
GetPatientExams(patientId);
}
private void GetPatientExams(string pid)
{
DataTable exams = "Get exam data from db by pid";
dtlExams.DataSource = exams;
dtlExams.DataBind();
//////////////// tree view
TreeNode tnnn;
foreach (DataRow row in exams.Rows)
{
tnnn = new TreeNode(exams["PRODSHORT"].ToString());
tvExams.Nodes.Add(tnnn);
}
}

Related

asp.net C# Gridview nested gridview

Dear all genius please help me with this had been trying everywhere but no luck. I am trying to open my nested gridview for a single Parent Row but gets open the entire parent row with one single record of the child row. It should be when I click the button of the Parent gridview row then the record for the particular row should display in the Child gridview in the same Parent row, but in my case the record of the Parent row shows up and the Child gridview gets open in all the parent row. Please need in help :(
enter image description here
<asp:GridView runat="server" ID="GridView4" AllowPaging="True"
AutoGenerateColumns="False" DataKeyNames="UId" class="" CellPadding="4" PageSize="5">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="File Type" Visible="false">
<ItemTemplate>
<asp:Label ID="lblFileType" runat="server" Text='<%# Eval("FileType") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="10%" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="10%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Image Name" Visible="false">
<ItemTemplate>
<asp:Label ID="lblImageName" runat="server" Text='<%# Eval("ImageName") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="10%" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="10%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="Image2" class="img1" runat="server" ImageUrl='<%# Bind("pic") %>' OnCommand="blah_Command" CommandName='<%# Eval("UId") %>' CommandArgument='<%# Eval("pic") %>' />
<asp:Panel ID="pnlOrders" runat="server" Style="position: relative" Visible="false">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="FileSize" HeaderText="Order Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="ShareByUserId" HeaderText="Date" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#ffffff" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#ffffff" Font-Bold="True" ForeColor="White" />
</asp:GridView>
Code Behind:
protected void blah_Command(object sender, CommandEventArgs e)
{
foreach (GridViewRow row2 in GridView4.Rows)
{
row2.FindControl("pnlOrders").Visible = true;
string customerId = e.CommandName.ToString();
GridView gvOrders = row2.FindControl("gvOrders") as GridView;
BindOrders(customerId, gvOrders);
}
}
private void BindOrders(string customerId, GridView gvOrders)
{
gvOrders.ToolTip = customerId;
gvOrders.DataSource = GetData(string.Format("select * from SShare where UId='{0}'", customerId));
gvOrders.DataBind();
}
You are looping all the rows in GridView4, so every nested GridView will be filled with data.
What you need is the row number of the row that the clicked LinkButton is in, and use that to find the nested GridView.
protected void blah_Command(object sender, CommandEventArgs e)
{
//get the current datagrid item from the sender
GridViewRow row = (GridViewRow)(((Control)sender).NamingContainer);
//the row index of the gridviewrow
int rowIndex = row.RowIndex;
//find the correct nested grid using the row index
GridView gvOrders = GridView4.Rows[rowIndex].FindControl("gvOrders") as GridView;
}

Select complete rows from a gridview using a checkbox and transfer to another webform

I need help to select information from a gridview not to delete, I´ve seen multiple ways to delete and I've tried to adapt it to my code but I'm having some issues with it,
This is my gridview code
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ItemStyle-Width="150px" ID="cbSelect" runat="server" AutoPostBack="True" OnCheckedChanged="cbSelect_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ItemStyle-Width="150px" ID="cbSelected" runat="server" AutoPostBack="True" OnCheckedChanged="cbSelected_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Poliza">
<ItemTemplate>
<asp:Label ID="Poliza" runat="server" Text='<%# Bind("POLIZA") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="RAMO"
HeaderText="Ramo" />
<asp:BoundField ItemStyle-Width="150px" DataField="CERTIF"
HeaderText="Certificado" />
<asp:BoundField ItemStyle-Width="150px" DataField="NOMRMO"
HeaderText="Ramo" />
<asp:BoundField ItemStyle-Width="150px" DataField="CIA"
HeaderText="N. Comp" />
<asp:BoundField ItemStyle-Width="150px" DataField="NOMCIA"
HeaderText="Compañia" />
<asp:BoundField ItemStyle-Width="150px" DataField="RIF"
HeaderText="Ident" />
<asp:BoundField ItemStyle-Width="150px" DataField="CCT"
HeaderText="Num" />
</Columns>
</asp:GridView>
In my backend I have the code that fills the gridview which is working perfectly, also the code that evaluates if the checkbox has been checked.
Now, this is the code of my button that needs to pick the value of all the rows and transfer to another webform, normally I have done it with a "buttonfield" with "OnSelectedIndexChanged" but I can I do it with a checkbox?
protected void Button2_Click(object sender, EventArgs e)
{
List<string> test = new List<string>();
foreach (GridViewRow gridViewRow in GridView2.Rows)
{
if (((CheckBox)gridViewRow.FindControl("cbSelected")).Checked)
{
string ejecutivoId = ((Label)gridViewRow.FindControl("Poliza")).Text;
test.Add(ejecutivoId);
}
}
if (test.Count > 0)
{}
Yes you can.
Fills the gridview and do the same as you did with Button Click, but with theOnCheckedChanged event.

Getting value of a cell from a GridView on SelectedIndexChanged event of DropDownList

I have a GridView that has data bounded rows. I'm trying to get specific cell value on the SelectedIndexChanged event of DropDownList. My tries are as follows:
string temp= GridView2.SelectedRow.Cells[3].Text;
string temp = ((DataBoundLiteralControl)GridView2.Rows[0].Cells[3].Controls[0]).Text;
DataBoundLiteralControl dblc = (DataBoundLiteralControl)GridView2.Rows[0].Cells[3].Controls[0];
string temp=dblc.Text;
These all 3 of them returns null.
Moreover, the Control[0] is returning correct value of TemplateFields only, but not DataBound fields.
.aspx
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor=" #d54d7b" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#FFFAFC" AlternatingRowStyle-BackColor="#FFFFF7" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging" Width="900px" Font-Names="Segoe UI Light" BorderColor="#DEDEDE">
<RowStyle HorizontalAlign="center" />
<Columns>
<asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="80" />
<asp:BoundField DataField="Vacancies" HeaderText="Vacancies" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Detail">
<ItemTemplate>
<asp:BoundField DataField="Date" HeaderText="Date" ItemStyle-Width="80" />
<asp:BoundField DataField="Time" HeaderText="Time" ItemStyle-Width="80" />
</Columns>
Problem you are probably facing is that, GridView1 hasn't been bounded yet.. that is the reason why Control[0] is returning correct value of TemplateFields but cells in the gridview returns null.
You can do the following
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
/// send value to filter or bind gridView1
/// bind gridvew
string temp = GridView1.Rows[0].Cells[3].Text;
/// or any code to get values from GridView Cell
}
I Converted all <asp:BoundFields> to <asp:TemplateField> and it looked like this:
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor=" #009C0D" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#FFFAFC" AlternatingRowStyle-BackColor="#FFFFF7" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" AllowPaging="true" CssClass="test"
HtmlEncode="true"
Font-Names="Segoe UI Light" BorderColor="#DEDEDE" >
<RowStyle HorizontalAlign="center" />
<Columns>
<asp:TemplateField HeaderText="Description" ControlStyle-Width="250px" ><ItemTemplate> <asp:LinkButton ID= "Description" PostBackUrl='<%# Eval("Description", "~/{0}.aspx") %>' Text='<%# Eval("Description")%>' runat="server" ></asp:LinkButton> </ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Vacancies"><ItemTemplate> <asp:Label ID="Vacancies" Text='<%# Eval("Vacancies")%>' runat="server" ></asp:Label> </ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Detail"><ItemTemplate><asp:Label ID="City" Text='<%# Eval("City")%>' runat="server" ></asp:Label> <div style="font-size:10px"> <asp:Label ID="Label1" Text='<%# Eval("DateDay")%>' runat="server" ></asp:Label> </div> </ItemTemplate></asp:TemplateField>
//and others
</Columns>
</asp:GridView>
And get specific value by entering this code behind DropDownList:
if (dropdown.SelectedIndex != -1)
{
ListItem mySelectedItem = (from ListItem li in dropdown.Items where li.Selected == true select li).First();
foreach (GridViewRow rw in GridView2.Rows)
{
Label tv = (Label)rw.Cells[3].FindControl("City");
if (tv.Text.IndexOf(mySelectedItem.Text) != -1)
{
rw.Visible = true;
}
else
rw.Visible = false;
}
}

Create a dynamic column in gridview while page upload

I want to add a column to my gridview while page is uploading.
My gridview takes his data from SQL static tables... and I want to add a column which contains the number of the row (1,2,3...)
Part of my gridview:
<asp:GridView ID="GridView1" runat="server" HorizontalAlign="Center"
AutoGenerateColumns="False" DataKeyNames="InjuryScenario_id"
DataSourceID="SqlDataSource30"
OnSelectedIndexChanged="GridView1_OnSelectedIndex" ShowHeaderWhenEmpty="True"
CellPadding="3" GridLines="None" BackColor="White" BorderColor="White"
BorderStyle="Ridge" BorderWidth="2px" CellSpacing="1">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="InjuryScenario_id" HeaderText="מספר תרחיש" ReadOnly="True" SortExpression="InjuryScenario_id" />
<asp:BoundField DataField="Cause_name" HeaderText="מנגנון" SortExpression="Cause_name" />
<asp:BoundField DataField="City_name" HeaderText="יישוב" SortExpression="City_name" />
<asp:BoundField DataField="Place_name" HeaderText="מקום" SortExpression="Place_name" />
<asp:BoundField DataField="InjuryDay" HeaderText="יום" SortExpression="InjuryDay" Visible="False"/>
<asp:BoundField DataField="InjuryMonth" HeaderText="חודש" SortExpression="InjuryMonth" Visible="False"/>
<asp:BoundField DataField="InjuryYear" HeaderText="שנה" SortExpression="InjuryYear" Visible="False"/>
<asp:TemplateField HeaderText="תאריך">
<ItemTemplate>
<asp:Label ID="Label1" runat="server"><%#(int)Eval("InjuryDay")+"/"+ Eval("InjuryMonth")+"/"+ Eval("InjuryYear") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I've tried to use this method:
protected void Btn_AddCol_Click(object sender, EventArgs e)
{
TemplateField tf = new TemplateField();
tf.HeaderTemplate = new GridViewLabelTemplate(DataControlRowType.Header, "Col1", "Int32");
tf.ItemTemplate = new GridViewLabelTemplate(DataControlRowType.DataRow, "Col1", "Int32");
GridView1.Columns.Add(tf);
}
Thanks

Binding Drop down in grid view programatically

<asp:GridView ID="gvStates" AutoGenerateColumns="false" Width="100%" AllowSorting="true"
runat="server" OnRowCreated="gvStates_RowCreated"
OnRowDataBound="gvStates_RowCreated">
<HeaderStyle BackColor="#57768f" ForeColor="White" />
<RowStyle BackColor="#dae2e8" ForeColor="Black" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="#ffffff" ForeColor="Black" />
<Columns>
<asp:BoundField HeaderText="key" DataField="key" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Quota" DataField="Quota" />
<asp:BoundField HeaderText="Session" DataField="Sess" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:DropDownList ID="ddlSess" Width="100%" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddl">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Scheduled">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%#Bind("Sched")%>' Enabled="false" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%#Bind("Sched")%>' />
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button ID="_b_SchStat" runat="server" AutoPostBack="true" Text="UnSchedule" OnClick="_b_ToggleSched" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Recruiter">
<ItemTemplate>
<asp:DropDownList ID="ddRec" Width="100%" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddR">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="MN Phone" DataField="MN Phone" />
<asp:BoundField HeaderText="Cell Phone" DataField="Cell Phone" />
</Columns>
</asp:GridView>
[dbo].[QRY_RecruitGrid]
#jobnum varchar(20),
#quota varchar(10),
#sess VARCHAR(10)
AS
SELECT
[job_resp_recordid] as 'key'
,[job_resp_name] as 'Name'
,[job_resp_quota] as 'Quota'
,[job_resp_session] as 'Sess'
,[job_resp_scheduled] as 'Sched'
,COALESCE([job_resp_recruited_by], '') as 'Recruiter'
,case when len(ltrim(rtrim([job_resp_phone])))='10' then '('+SUBSTRING([job_resp_phone],1,3)+')'+' '+SUBSTRING([job_resp_phone],4,3)+'-'+SUBSTRING([job_resp_phone],7,4) when len(ltrim(rtrim([job_resp_phone])))='' then ' ' end AS [MN Phone]
,case when len(ltrim(rtrim([job_resp_cellphone])))='10' then '('+SUBSTRING([job_resp_cellphone],1,3)+')'+' '+SUBSTRING([job_resp_cellphone],4,3)+'-'+SUBSTRING([job_resp_cellphone],7,4) when len(ltrim(rtrim([job_resp_cellphone])))='' then ' ' end AS [Cell Phone]
FROM [dbo].[tbl_job_respondents]
WHERE job_resp_job_number like #jobnum
and job_resp_quota like #quota
AND job_resp_session LIKE #sess
order by job_resp_quota, [job_resp_name]
I'm trying to bind the 'ddRec' dropdown to the Recruiter field in the dataset. I tried
DataTextField='<%#Bind("Recruiter")%>'
Edit:
Error: {"Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control."}
Let me explain better sorry. I'm trying to set the value from the proc but the dropdown list itself is being populated from a query on the OnRowCreated Event I think this is my problem
protected void gvStates_RowCreated(object sender, GridViewRowEventArgs e)
{
var drop = new List<string> { "" };
var LNQ = new LNQDataContext();
var Rec = LNQ.Recruits.Where(c => c.Active == "Y").Select(c => new { c.Name });
var Rdp = new List<string> { "" };
foreach (var a in Rec) { Rdp.Add(a.Name); }
for (int i = 1; i <= _cnt; i++) { drop.Add("S" + i); }
if (e.Row.RowType == DataControlRowType.DataRow)
{
var ddl = (DropDownList)e.Row.FindControl("ddlSess");
ddl.DataSource = drop;
ddl.DataBind();
var ddR = (DropDownList)e.Row.FindControl("ddRec");
ddR.DataSource = Rdp;
ddR.DataBind();
}
}
You can't programmatically bind to the DataTextField field; the DataTextField identifies the field to display in the drop down, hence it has to be static and is not evaluated per row. Though, you can tap into the Grid's RowDataBound event, and programmably set the DataTextField property and bind data at that point.
HTH.

Categories