How to implement onclick row selection on gridview - c#

Can someone help me, I am new at using asp.net. I have a table that is filled with data and if the user clicks on a row, the data inside the selected row will populate the input fields. I Have created a c# code using onclick row selection in grid view, it is working but it can only select one row and if you select another row it doesn't select it and it stays on whatever you clicked first. how can I select the other rows using onclick?
this is the html gridview code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="CASE_KEY" DataSourceID="SqlDataSource1" Height="250px"
Width="1109px" BackColor="White" BorderColor="#999999" BorderStyle="None"
BorderWidth="1px" CellPadding="3" GridLines="Vertical" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="Gainsboro" />
<Columns>
<asp:BoundField DataField="CASE_KEY" HeaderText="CASE_KEY" ReadOnly="True"
SortExpression="CASE_KEY" Visible="False" />
<asp:BoundField DataField="DEPARTMENT_CASE_NUMBER"
HeaderText="Department Case #" SortExpression="DEPARTMENT_CASE_NUMBER" />
<asp:BoundField DataField="DEPARTMENT_NAME" HeaderText="Department"
SortExpression="DEPARTMENT_NAME" />
<asp:BoundField DataField="CHARGE" HeaderText="Charge"
SortExpression="CHARGE" />
<asp:BoundField DataField="LAB_CASE" HeaderText="Lab Case #"
SortExpression="LAB_CASE" />
<asp:BoundField DataField="OFFENSE_DATE" HeaderText="Incident Report Date"
SortExpression="OFFENSE_DATE" />
</Columns>
This is the html input fields
<table class="style2">
<tr>
<td class="style3">
Department Case #</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
Department</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
Charge</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
Lab Case #</td>
<td>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
Incident Report Date</td>
<td>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
</td>
</tr>
</table>
This is my c# code
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//Get the selected row
GridViewRow row = GridView1.SelectedRow;
if (row != null)
{
//Change the cell index(1) of column as per your design
//Get the Selected row cell values here
GridViewRow gr = GridView1.SelectedRow;
TextBox1.Text = gr.Cells[1].Text;
TextBox2.Text = gr.Cells[2].Text;
TextBox3.Text = gr.Cells[3].Text;
TextBox4.Text = gr.Cells[4].Text;
TextBox5.Text = gr.Cells[5].Text;
}
}
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Change the mouse cursor to Hand symbol to show the user the cell is selectable
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';this.style.cursor='Pointer'";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
//Attach the click event to each cells
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}
}

Your solution is almost right except for the fact that you should use the rowCommand event of the GridView instead of the selectedIndexChange and then your solution should work

Related

How to display selected row value/text inside the dropdown

So I am new to using ASP.net and i have a hard time displaying the value/text of the selected row inside the dropdown. I just want to select a row in the griview and when i select, the values in it should populate the textboxes and dropdown, can someone help me ? thanks
this is my code behind, as you can see in the LoadData() part I used the .findtext() but it outputs an error :Object reference not set to an instance of an object.
protected void grdRecentCases_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';this.style.cursor='Pointer'";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grdRecentCases, "Select$" + e.Row.RowIndex);
}
}
protected void grdRecentCases_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
LoadData(Convert.ToInt32(e.CommandArgument));
}
}
///<summary> LoadData is used to populate inputboxes with the value of the selected griview row</summary>
///<param name="rowNumber"> Indicates whether there is a selected row or non</param>
private void LoadData(int? rowNumber = null)
{
//if rowNumber is null use GridView1.SelectedIndex
var index = rowNumber ?? grdRecentCases.SelectedIndex;
//Populate the input box with the value of selected row.
GridViewRow gr = grdRecentCases.Rows[index];
txtDepartmentCase.Text = gr.Cells[2].Text;
txtLabCase.Text = gr.Cells[5].Text;
txtIncidentReportDate.Text = gr.Cells[6].Text;
txtCaseKey.Text = gr.Cells[1].Text;
drpDepartment.Items.FindByText(gr.Cells[3].Text).Selected = true;
drpCharge.Items.FindByText(gr.Cells[4].Text).Selected = true;
}
Html code
<table class="style2">
<tr>
<td class="style3">
Department Case #
</td>
<td>
<asp:TextBox ID="txtDepartmentCase" runat="server" Enabled="False"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
Department
</td>
<td>
<asp:DropDownList ID="drpDepartment" runat="server" Height="18px" Width="153px" Enabled="False"
AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="drpDepartment_SelectedIndexChanged"
Visible="true">
</asp:DropDownList>
<asp:TextBox ID="txtDepartment" runat="server" Enabled="False"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
Charge
</td>
<td>
<asp:DropDownList ID="drpCharge" runat="server" Height="22px" Width="153px" Enabled="False"
AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="drpCharge_SelectedIndexChanged"
Visible="true">
</asp:DropDownList>
<asp:TextBox ID="txtCharge" runat="server" Enabled="False"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
Lab Case #
</td>
<td>
<asp:TextBox ID="txtLabCase" runat="server" Enabled="False"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style3">
Incident Report Date
</td>
<td>
<asp:TextBox ID="txtIncidentReportDate" runat="server" Enabled="False"></asp:TextBox>
</td>
</tr>
</table>
As you mentioned, to select a row in the griview and when i select, the values in it should populate the textboxes and dropdown.
Hope this can help you.
Create a datagridview event, RowHeaderMouseClick
private void datagridview_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
string selectedDoc = datagridview.Rows[datagridview.SelectedRows[0].Index].Cells["column name"].Value.ToString() ;
combobox.Text = selectedDoc;
}

Label inside gridview is not showing any value

Label4 inside gridview is not displaying textbox value while Label5 outside gridview is showing the textbox value. Label4 Value is blank. I want that the label i.e Label4 should display Label5.Text.
<Columns>
<asp:TemplateField HeaderText="Place Details">
<ItemTemplate>
<table>
<tr>
<td>
<b>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("name") %>'></asp:Label>&nbsp&nbsp&nbsp&nbsp&nbsp
<asp:Label ID="Label2" runat="server" Text='<%# Eval("phno") %>'></asp:Label>
</b>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("zone") %>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label4" runat="server" Text="Label"></asp:Label>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<asp:Label ID="Label5" runat="server" Text="Label"></asp:Label>
Using Gridview Row Databound bind value of label4
Label Label4 = (Label)e.row.findcontrol("Label4");
Label4.text = (Your Value assign here)
so display your value
I've had this issue which disappeared when I commented out everything inside my GridView1_RowDataBound(object sender, GridViewRowEventArgs e) method. I was adding a tooltip to all cells in the row which I think overwritten it.
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
// var id = e.Row.Cells[0].Text;
//if (e.Row.RowType == DataControlRowType.DataRow)
//{
}

cannot find controls in gridview and get an error(Index was out of range)

Actually I have problem with finding LinkButton Control in gridview .
I have 2 gridviews which one of them is inside another one so my problem is I cannot get the value of LinkButton of second gridview,
here is my code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BorderStyle="None" DataSourceID="SqlDataSource2" GridLines="None">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<table align="center" class="Table3">
<tr>
<td >
<asp:Label ID="lblID" runat="server" Visible="false" Text='<%# Eval("Food_ID") %>'></asp:Label>
<b> <%#Eval("Title")%></b>
</td>
</tr>
<tr>
<td align="center" class="ImgKidFood">
<asp:Image ID="Img" Width="680px" Height="145px" ImageUrl='<%#Eval("Pictures") %>' runat="server" />
</td>
</tr>
<tr>
<td style="direction:rtl; text-align:right;">
<asp:GridView ID="ShowFoodMenu2" runat="server" AutoGenerateColumns="False"
BorderStyle="None" GridLines="None" ShowHeader="False"
DataSourceID="SqlDataSource1" Width="100%"
>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table align="center" class="TableListMenu">
<tr>
<td class="Add">
<asp:LinkButton ID="LinkButton2" CommandArgument="<%# Container.DataItemIndex %>"
runat="server" CausesValidation="False"
CommandName="Select" Text="Select"
onclick="LinkButton2_Click" ></asp:LinkButton>
</td>
<td class="ToCenter">
<b><%#Eval("Title_Pr") %>
</b>
<asp:LinkButton ID="LinkButton12" runat="server" CommandArgument="<%# Container.DataItemIndex %>" CommandName="Link2" Text='<%# Eval("Menu_ID") %>'></asp:LinkButton>
</td>
<td class="PriceLeft">
<%#Eval("Price") %>
</td>
</tr>
</table>
<hr />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br /><br /><br />
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
As u can see the second gidview named id is ShowFoodMenu2 and it's inside first girdview which id Giridview1 .
and also I have two Linkbuttons inside the second gridview
one of them keep the value(which is LinkButton12) and another one(LinkButton2) is for when I clicked it add a record in Database .
But when I clicked on Linkbutton(LinkButton2) to show the value of Linkbutton12 , I will get ann error
Here is the error
http://hidelion.com/Images/error.png
and here is my.cs code
protected void LinkButton2_Click(object sender, EventArgs e)
{
GridView G = new GridView();
G.FindControl("ShowFoodMenu2");
System.Threading.Thread.Sleep(1000);
LinkButton m = (LinkButton)sender;
int i = Int32.Parse(m.CommandArgument);
LinkButton LblMososID = (LinkButton)G.Rows[i].FindControl("LinkButton2");
// LinkButton LblMososID2 = (LinkButton)G.Rows[i].FindControl("LinkButton12");
Label1.Text = LblMososID.Text;
}
So how can I solved this problem ??????
GridView G = new GridView(); just create a new instance of Gridview class, and it will not find your gridview automatically, You are messing it up, simply go like this, from linkbutton find the corresponding row, from that row fetch the control you wish to manipulate, do it like this:-
protected void LinkButton2_Click(object sender, EventArgs e)
{
LinkButton LinkButton2 = sender as LinkButton;
GridViewRow grdRow = (GridViewRow)LinkButton2.NamingContainer;
LinkButton LinkButton12 = (LinkButton)grdRow.FindControl("LinkButton12 ");
Label1.Text = LinkButton12.Text;
}

Change header text in Rowdataboud of Gridview nested inside Repeater

I have a gridview nested inside a repeater, I want to change the header text of gridview columns on row databound or through
<HeaderTemplate>
<asp:Label runat="server" ID="lblMode" Text='<%# Eval("IsValidForPromoCode")%>'>
</asp:Label></HeaderTemplate>
whichever is convenient.
.aspx page
<asp:Repeater ID="repRequest" runat="server" OnItemDataBound="repRequest_ItemDataBound">
<ItemTemplate>
<table style="width: 100%; font-weight: bold;" cellpadding="5" cellspacing="0">
<tr>
<td colspan="12" align="right">
<a id="aSetPreference" runat="server" href="#">Attached Document(s)-</a>
<asp:Label ID="lblDocumentCount" CssClass="redFont" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="left" class="gray-bg" style="width: 8%;">
<b>Request#:</b>
</td>
<td style="width: 100px;">
<span class="detail-info-color">
<%# Eval("RequestNumber")%></span>
</td>
<td align="left" class="gray-bg" style="width: 5%;">
<asp:Label ID="lblreqDetID" runat="server" Visible="false" Text='<%# Bind("TravelDetailsID") %>'></asp:Label>
<b>Date:</b>
</td>
<td align="left" class="gray-bg" style="width: 5%;">
<b>Class:</b>
</td>
<td>
<span class="detail-info-color">
<%# Eval("Class")%></span>
</td>
</tr>
<tr>
<td colspan="12">
<asp:GridView ID="gvOption" CssClass="gridRow" runat="server" AutoGenerateColumns="False"
Width="100%" OnRowDataBound="gvOption_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="#">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Service Provider">
<ItemTemplate>
<asp:Label ID="txtNumber" runat="server" Width="80px" Text='<%# Bind("Number") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label runat="server" ID="lblMode" Text='<%# Eval("IsValidForPromoCode") %>'></asp:Label></HeaderTemplate>
<ItemTemplate>
<asp:Label ID="txtName" runat="server" Width="100px" Text='<%# Bind("Name") %>'></asp:Label>
<asp:Label ID="lblOptionID" Visible="false" runat="server" Width="100px" Text='<%# Bind("optionID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
Code behind
protected void gvOption_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
GridView gvOption = (GridView)sender;
if (e.Row.RowType == DataControlRowType.DataRow)
{
gvOption.Columns[1].HeaderText = "Last Name";
}
if (e.Row.RowType == DataControlRowType.Header)
{
gvOption.Columns[2].HeaderText = "Last Name";
}
}
catch (Exception ex)
{
throw ex;
}
}
Whichever way I am doing it's not effecting. Please suggest what I am missing.
Try this:-
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[1].Text = "Last Name";
}
Here, I have hard-coded the Cells value you need to change it accordingly.
Update:-
Find Control inside RowDataBound:-
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label txtNumber = (Label)e.Row.FindControl("txtNumber");
txtNumber.ForeColor = System.Drawing.Color.Red;
}

Add a user row to an existing grid or table on button click

I have created a page that has one GridView and one Form. My GridView is working properly.
My form has a TextBox for User Name or Email address and a submit button. This form is also working properly.
Below this form, I need to create a Table or Grid to store each User name and Email that was added.
How can I create this table that in such a way that one line is added for each btnSendUser_OnClick event? This table must not delete rows that were inserted previously.
My table now shows just one row (the most recent).
My aspx
<asp:GridView ID="GridView" runat="server" AutoGenerateColumns="false" GridLines="None"
CssClass="table table-bordered table-striped">
<Columns>
<asp:BoundField DataField="AccessGroup" HeaderText="Access Group" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Business Justification">
<ItemTemplate>
<asp:TextBox ID="txtJustBuss" runat="server" Height="17px" Width="150px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblUserAdd" runat="server" Font-Bold="true" Text="Add User - (Email or User Name)"></asp:Label>
<br />
<asp:TextBox ID="txtUserAdd" runat="server" Height="17px" Width="150px"></asp:TextBox>
<asp:Label ID="lblError" runat="server" class="control-label" for="inputError" Visible="false">Input with error</asp:Label>
<asp:Button ID="btnAddUser" class="btn" runat="server" Font-Bold="true" Text="Add User"
OnClick="btnSendUser_OnClick" />
<br />
<br />
<table id="tblUsers" class="table table-bordered table-striped" runat="server" visible="false">
<tbody>
<tr>
<td>
<asp:Label ID="lblUser" runat="server" Visible="false"></asp:Label>
</td>
<td>
<asp:Label ID="lblEmail" runat="server" Visible="false"></asp:Label>
</td>
</tr>
</tbody>
</table>
My .cs
protected void btnSendUser_OnClick(object sender, EventArgs e)
{
string LoginInfo = txtUserAdd.Text;
PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, "x.com", "amsuser", "xx");
UserPrincipal insUserPrincipal = UserPrincipal.FindByIdentity(insPrincipalContext, LoginInfo);
if (insUserPrincipal == null)
{
lblError.Visible = true;
}
else
{
tblUsers.Visible = true;
lblUser.Visible = true;
lblEmail.Visible = true;
lblUser.Text = insUserPrincipal.GivenName + " " + insUserPrincipal.Surname;
lblEmail.Text = insUserPrincipal.EmailAddress;
}
}
You should use a component that is designed to deal with a collection of values - for example another grid.
If that is too heavy, you can just update the labels like this:
lblUser.Text = lblUser.Text
+ insUserPrincipal.GivenName + " " + insUserPrincipal.Surname
+ "<br />";
lblEmail.Text = lblEmail.Text
+ insUserPrincipal.EmailAddress
+ "<br />";

Categories

Resources