why GridView1_SelectedIndexChanged not working?
i'm learning asp.net on my own(which means i learn through youtube) , using vs2015
created a grid of items and want to show the selected item in a textbox , but code doesn't do any change
i created empty project added masterpage and default page , and just added a text and grid , scriptmanager updatepanel contenttemplate. whenever i click select on any row from the grid textbox is still empty
MasterPage.master:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Default.aspx:
<%@ Page Title="" enableeventvalidation="true" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<style type="text/css">
.auto-style1 {
width: 100%;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table >
<tr>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:CommandField ButtonType="Button" ShowSelectButton="True" />
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Default.aspx.cs:
using System;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable tbl = new DataTable();
tbl.Columns.Add("serial");
for (int i = 0; i < 4; i )
{
DataRow row = tbl.NewRow();
row[0] = i 1;
tbl.Rows.Add(row);
}
GridView1.DataSource = tbl;
GridView1.DataBind();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = GridView1.SelectedRow.Cells[0].Text;
}
}
CodePudding user response:
You are selecting the wrong cell on the SelectedIndexChanged method.
The first Cell (index 0) contains the button, so you want the second cell (index 1).
You should place a breakpoint on the method and see for yourself what other properties are filled in the GridView.