Passing gridview row data to textboxes on selection of gridview row - c#

I can't seem to make data from my gridview pass to textboxes outside of my gridview on row selection. The event seems to be firing, but the textboxes are always filled with & nbsp;. I can't figure out why this is happening since none of the cells in the gridview are blank. I have been researching this problem for a few days, on this site and other sites, with no luck. Here is the piece of my aspx.cs:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
txtBLName.Text = GridView1.Rows[GridView1.SelectedIndex].Cells[1].Text;
}
Here is my gridview code:
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="False"
onselectedindexchanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:CommandField ShowSelectButton="true" SelectText="Edit" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName"/>
</Columns>
</asp:GridView>
Can someone please help? Thanks!

It's Working
ASP CODE
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:GridView ID="GridView2"
runat="server"
AutoGenerateColumns="False"
onselectedindexchanged="GridView2_SelectedIndexChanged" >
<Columns>
<asp:CommandField ShowSelectButton="true" SelectText="Edit" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName"/>
</Columns>
C# CODE
protected void Page_Load(object sender, EventArgs e)
{
DataTable oDT = new DataTable();
oDT.Columns.Add("edit",typeof(string));
oDT.Columns.Add("LastName", typeof(string));
oDT.Rows.Add("ad", "1212121");
oDT.Rows.Add("aad", "1asdasd212121");
GridView2.DataSource = oDT;
GridView2.DataBind();
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView2.SelectedRow;
TextBox1.Text = row.Cells[1].Text;
}
RESULT

Related

RowIndex of row of which dropdown was selected

Reference image of the GV
So OnSelectedIndexChanged of the dropdown in 7th cell I want to enable or disable the Remarks column (last column) of that row
Gridview.aspx
<asp:GridView ID="grdassetslist" runat="server" AutoGenerateColumns="false" BackColor="Transparent" BorderColor="Black" BorderStyle="Dashed" BorderWidth="1px" CellPadding="4"
DataKeyNames="ID" AutoGenerateSelectButton="true" CellSpacing="2" OnRowDataBound="grdassetslist_RowDataBound" HeaderStyle-ForeColor="Black" HeaderStyle-BackColor="#66ccff"
OnSelectedIndexChanged="grdassetslist_SelectedIndexChanged" HorizontalAlign="Center" HeaderStyle-CssClass="grd" RowStyle-CssClass="grd" AllowPaging="true" PageSize="15"
OnPageIndexChanged="grdassetslist_PageIndexChanged" OnPageIndexChanging="grdassetslist_PageIndexChanging">
<Columns>
<asp:TemplateField Visible="false" >
<ItemTemplate>
<asp:HiddenField ID="hdnAstID" runat="server" Visible="false" Value='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Code" HeaderText="Asset Category" ReadOnly="true" />
<asp:BoundField DataField="SAPAssetCode" HeaderText="SAP Asset Code" ReadOnly="true" />
<asp:BoundField DataField="ITAssetCode" HeaderText="IT Asset Code" ReadOnly="true" />
<asp:BoundField DataField="Make" HeaderText="Make" ReadOnly="true" />
<asp:BoundField DataField="ModelNo" HeaderText="ModelNo" ReadOnly="true" />
<asp:BoundField DataField="InvoiceDate" HeaderText="Invoice Date" ReadOnly="true" />
<asp:BoundField DataField="AssetStatus" HeaderText="Current Status" ReadOnly="true" />
<asp:TemplateField HeaderText="Change Status To">
<ItemTemplate>
<asp:DropDownList ID="ddl_each_asset_status" runat="server" Width="100px" Height="25px" CssClass="dd" AutoPostBack="true" OnSelectedIndexChanged="ddl_each_asset_status_SelectedIndexChanged1" CausesValidation="false" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CurrentUser" HeaderText="CurrentUser" ReadOnly="true" />
<asp:TemplateField HeaderText="Remarks for Status change">
<ItemTemplate>
<asp:TextBox ID="txtrmrks" runat="server" placeholder="Remarks (if any)" ReadOnly="true"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="Assests" HeaderText="" ReadOnly="true" />--%>
</Columns>
<HeaderStyle HorizontalAlign="Center"/>
<PagerStyle HorizontalAlign="Center" />
</asp:GridView>
GridLoad.apx.cs
con.Open();
DropDownList DropDownList1 = (e.Row.FindControl("ddl_each_asset_status") as DropDownList);
SqlCommand cmd = new SqlCommand("select ID,Code[Title] from tbl_assetstatus (nolock) where ID<>2 and IsActive=1 order by ID", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Title";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select Status", "0"));
SelectedIndexChanged event:
protected void ddl_each_asset_status_SelectedIndexChanged1(object sender, EventArgs e)
{
//Code to Enable or Disable the remarks column of that row of which the dropdown was changed?
}
Please add the code for SelectedIndexChanged for this.
Thanks in Advance
If you using GridView, then I doubt this is a .net core application?
And really, to help us out here - try posting at LEAST SOME of your gridviewe markup, as then we not trying to play a game of darts in a room with the lights out.
Assuming a GV like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID"
CssClass="table table=table-hover" Width="800px"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Firstname" HeaderText="First name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:TemplateField HeaderText="Select Hotel City">
<ItemTemplate>
<asp:DropDownList ID="cboCity" runat="server" Width="120px" Height="26px"
DataTextField="City"
DataValueField="City"
AutoPostBack="true"
OnSelectedIndexChanged="cboCity_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="Description" HeaderText="Description" />
</Columns>
</asp:GridView>
</div>
<div style="float:left;margin-left:20px">
<asp:Label ID="lbl1" runat="server" Height="179px" Width="450px" TextMode="MultiLine">
</asp:Label>
</div>
Code to load:
DataTable rstCity = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL =
"SELECT City FROM City ORDER BY City";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rstCity.Load(cmdSQL.ExecuteReader());
cmdSQL.CommandText =
"SELECT * FROM tblHotelsA ORDER BY HotelName";
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
Ok, and now the code for the combo box (dropdown list). We assume auto-post back, so the code is thus this:
protected void cboCity_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList cboCity = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)cboCity.NamingContainer;
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
string cr = System.Environment.NewLine;
string sResult =
$"Row index = {gRow.RowIndex} \n DataBase PK = {PK} <br/>" +
$" Hotel = {gRow.Cells[3].Text} <br/>" +
$"Combo Box selection = {cboCity.Text}";
lbl1.Text = sResult;
}
and thus we see/get this:
Edit2:
I should also note the following additonal information:
Of course I have to fill/load the drop down.. and that is done in row data bound event. Eg this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView gData = (DataRowView)e.Row.DataItem;
DropDownList cboCity = (DropDownList)e.Row.FindControl("cboCity");
cboCity.DataSource = rstCity;
cboCity.DataBind();
cboCity.Items.Insert(0,new ListItem("Select", ""));
if (gData["City"] != DBNull.Value)
{
cboCity.Text = gData["City"].ToString();
}
}
}
Also, note how I don't care (or bother) with the GV selected index changed event. I really don't need it. I as noted, simple set autopost-back = true.
Last but not least?
you of course cannot build ANY working webforms page if you attemptto load up data in on-load but FORGET to check isPostback.
Since any button click, any post-back, or anything causing a post-back will of course trigger the page load event again, and BEFORE any of your other events. Thus, you need to ALWAYS ensure that you only load up the information one time on page load, since if you re-load the gv, or even a dropdown, then you tend to lose that choice by the user being made.
thus, that all imporant !IsPostBack stub is required for most pages.
Eg this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
next up:
Since the dropdown list has the one grid row, then you are free to get data, hide data, enable or do whatever you please.
Just keep in mind that
For built in "databound" columns, you use the cells[] colleciton.
For any templated control, then you use gRow.FindControl("control name here")
So, since your "goal" in question is to operate on "txtrmrks" then that is a templated column, and thus we have to use findcontrol.
Say, like this:
air code warning!!!
protected void cboCity_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList cboCity = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)cboCity.NamingContainer;
TextBox txtrmrks = (TextBox)gRow.FindControl("txtrmrks");
if (cboCity.Text == "Banff")
{
// disable the txtrmrks box
txtrmrks.Enabled = false;
}
}
You also not clear if you are going to working the value returned from the cbo box as "id", or "Title"
I suggest this way, and not to use ".Text" of the cbo, but this:
cboCity.SelectedItem.Value (gets value - ID)
cboCity.SelectedItem.Text (gets Text - Title)
if (cboCity.SelectedItem.Text)

displaying images from a folder in a gridView ASP.NET

How can I display images in GridView from a folder in my project?
Iv'e tried to create an image/imageField dynamically, but it didn't work- I don't know how to connect the images to the imageField in my GridView, and that's my main problem.
How can I do it?
Here's my GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="271px" onselectedindexchanged="GridView1_SelectedIndexChanged"
style="font-family: Arial, Helvetica, sans-serif" Width="452px">
<Columns>
<asp:BoundField DataField="messageSubject" HeaderText="subject" />
<asp:BoundField DataField="messageContent" HeaderText="content" />
<asp:BoundField DataField="wasReadOrNot" HeaderText="was read" />
<asp:ImageField HeaderText="image">
</asp:ImageField>
</Columns>
</asp:GridView>
(In addition, it's okay to use imageField at all?)
And here's my Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
Page.MaintainScrollPositionOnPostBack = true;
if (!IsPostBack)
{
WebServiceDBMessages.WebServiceDBMessagesSoapClient dbm = new WebServiceDBMessages.WebServiceDBMessagesSoapClient();
DataTable dt = dbm.ReturnAllMessagesForTeacher(Session["teacher"].ToString()).Tables[0];
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (GridView1.Rows[i].Cells[3].Text == "not read")
{
//here i want to display image whose url is: "/images/notRead.png"
}
else
{
//here i want to display image whose url is: "/images/read.png"
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Thanks(:
The image url is not in the dataset so can change your GridView definition to
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="271px" onselectedindexchanged="GridView1_SelectedIndexChanged"
style="font-family: Arial, Helvetica, sans-serif" Width="452px" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="messageSubject" HeaderText="subject" />
<asp:BoundField DataField="messageContent" HeaderText="content" />
<asp:BoundField DataField="wasReadOrNot" HeaderText="was read" />
<asp:TemplateField HeaderText="image">
<ItemTemplate>
<asp:Image runat="server" ID="img" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Change your page load to
protected void Page_Load(object sender, EventArgs e)
{
Page.MaintainScrollPositionOnPostBack = true;
if (!IsPostBack)
{
WebServiceDBMessages.WebServiceDBMessagesSoapClient dbm = new WebServiceDBMessages.WebServiceDBMessagesSoapClient();
DataTable dt = dbm.ReturnAllMessagesForTeacher(Session["teacher"].ToString()).Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Add following
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var image = e.Row.FindControl("img") as Image;
image.ImageUrl = e.Row.Cells[3].Text == "not read" ? "/images/notRead.png" : "/images/read.png";
}
}
This should accomplish what you are trying to do.

HyperLink to specific item in gridview row

So I am working on a basketball website. There is a gridview full of teams and what I would like is when you click on a team name, it links you to a new page that has info about the team. What I tried so far only links every team to the same details page.
Here is my gridview code:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Team"
DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None"
Height="340px" Width="776px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:HyperLinkField DataTextField="Team" DataNavigateUrlFields="Rank" DataNavigateUrlFormatString="~/MemberPages/Details.aspx?Rank={0}"
HeaderText="Team" SortExpression="Team" ItemStyle-Width = "150" >
<ItemStyle Width="150px"></ItemStyle>
</asp:HyperLinkField>
<asp:BoundField DataField="Rank" HeaderText="Rank" SortExpression="Rank" />
<asp:BoundField DataField="PointsPerGame" HeaderText="PointsPerGame"
SortExpression="PointsPerGame" />
<asp:BoundField DataField="OpponentPointsPerGame"
HeaderText="OpponentPointsPerGame" SortExpression="OpponentPointsPerGame" />
<asp:BoundField DataField="TopPlayer" HeaderText="TopPlayer"
SortExpression="TopPlayer" />
</Columns>
</asp:GridView>
And here is what I tried in the cs file to databind them to a specific link:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Team"),new DataColumn("Ranking"), new DataColumn("PointsPerGame"),
new DataColumn("OpponentPointsPerGame"), new DataColumn("TopPlayer")});
GridView1.DataBind();
}
}
For that kind of show/hide logic on specific row, you will need to use GridView.RowDataBound event.
Use a TemplateField instead of BoundField.
Place HyperLink control inside.
Then retrieve the HyperLink control inside RowDataBound event.
Example Code
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" ID="MyHyperLink" Text="My Text" />
</ItemTemplate>
</asp:TemplateField>
protected void GridView1_RowDataBound(
Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var myHyperLink = e.Row.FindControl("MyHyperLink") as HyperLink;
if(SOME_LOGIC)
{
myHyperLink.Visible = false;
}
}
}

Get Value from ASP.NET GridView cell

How would I get the value from a GrivView cell when the edit button is clicked?
I have tried other answer but none seem to work.
I would like to be able to get the value of Questionnaire ID for the row when the edit button is pressed.
Here is the gridview im working with.
<asp:GridView runat="server" ID="gvShowQuestionnaires" HeaderStyle-CssClass="table_header" CssClass="view" AlternatingRowStyle-CssClass="alt" AutoGenerateColumns="False"
DataKeyNames='QuestionnaireID' OnRowDeleting="gvShowQuestionnaires_RowDeleting" OnRowEditing="edit" ShowFooter="true" FooterStyle-CssClass="view_table_footer">
<Columns>
<asp:BoundField DataField="QuestionnaireID" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField>
<asp:BoundField DataField="QuestionnaireName" HeaderText="Questionnaire Name" />
<asp:TemplateField HeaderText="Results" HeaderStyle-Width="150px"></asp:TemplateField>
<asp:CommandField HeaderText="Options" ShowDeleteButton="True" ShowEditButton="true" ItemStyle-CssClass="cart_delete">
</asp:CommandField>
</Columns>
</asp:GridView>
<asp:label ID="ab" runat="server"></asp:label>
The backend
protected void edit(object sender, GridViewEditEventArgs e)
{
string c = gvShowQuestionnaires.Rows[index].Cells[0].Text;
ab.Text = c;
}
The GridViewEventArgs has the index of the row being edited. It doesn't look like you are using the index from the event args. Try this:
protected void edit(object sender, GridViewEditEventArgs e)
{
string c = gvShowQuestionnaires.Rows[e.NewEditIndex].Cells[0].Text;
...
}
If you give your field an ID, you should be able to get it by calling
e.item.FindControl("fieldId").

Accessing GridView data from a templatefield

<asp:GridView ID="gvGrid" runat="server" AutoGenerateColumns="False"
DataSourceID="dsDataSource" AllowPaging="True" PageSize="20" >
<Columns>
<asp:BoundField DataField="Field1" HeaderText="Field1"
SortExpression="Field1" />
<asp:BoundField DataField="Field2" HeaderText="Field2"
SortExpression="Field2" />
<asp:TemplateField HeaderText="TemplateField1">
<ItemTemplate>
<asp:Label id="lblComments" runat="server" Text=" i use a function to compute"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" SelectText="Complete" HeaderText ="Status" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnComplete" runat="server" Text="Complete" onclick="btnComplete_Click"/>
<asp:Button ID="btnAddComment" runat="server" Text="Add Comment" onclick="btnAddComment_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void btnComplete_Click(object sender, EventArgs e)
{
String Field1 = gvGrid.SelectedRow.Cells[1].Text; // throws an error at runtime
//I want to be able to access the row data do some computation and then be able to insert it into the database
// Reason why I am trying to use it as a template field instead of a commandfield is because I want to make it not visible when it meets certain condition.
}
Also, it would be great if you could let me know a better way to do it, maybe using the command field and if there is a way to toggle its visibility. I don't mind using LinkButton either.
You can do it like this:
protected void btnComplete_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvRow = (GridViewRow)btn.Parent.Parent;
//Alternatively you could use NamingContainer
//GridViewRow gvRow = (GridViewRow)btn.NamingContainer;
Label lblComments = (Label)gvRow.FindControl("lblComments");
// lblComments.Text ...whatever you wanted to do
}
here is how you can access to the gridview row:
protected void btnComplete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvGrid.Rows)
{
Label lblComments = row.FindControl("lblComments") as Label;
....//you can do rest of the templatefiled....
}
}

Categories

Resources