I have tried several so called answers for this and it has me lost. I am simply trying to default a TextBox Text value with today's date and time, but I cannot find the control when I click LinkButton with CommandName "Edit".
Here is my gridview...
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3"
DataSourceID="sdsSignInRegister" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" GridLines="Vertical" OnRowCommand="gvSignInRegister_RowCommand1">
<Columns>
<asp:TemplateField HeaderText="Returned" SortExpression="DateTimeReturned">
<EditItemTemplate>
<asp:TextBox ID="txtReturned" runat="server"></asp:TextBox>
<asp:ImageButton runat="Server" ID="calImg" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" CausesValidation="False" />
<asp:RequiredFieldValidator ID="rfv1" runat="server" SetFocusOnError="true" ValidationGroup="vg1" ControlToValidate="txtReturned" ErrorMessage="Required"></asp:RequiredFieldValidator>
<ajaxToolkit:CalendarExtender ID="ce1" runat="server" PopupButtonID="calImg" Enabled="true" Format="dd/MM/yyyy" TargetControlID="txtReturned" PopupPosition="TopRight" OnClientDateSelectionChanged="AppendTime"></ajaxToolkit:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Eval("DateTimeReturned","{0:dd/MM/yyyy HH:mm}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="btnCAN" runat="server" CausesValidation="false" CommandName="Cancel" Text="CANCEL" />
<asp:Button ID="btnUPD" runat="server" ValidationGroup="vg1" CausesValidation="true" CommandName="Update" Text="UPDATE" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btnEDT" runat="server" CausesValidation="false" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>' Text="SIGN IN" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
The LinkButton btnEDT works and puts the gridview in edit mode. But in code behind I cannot find "txtReturned".
This is what I've tried so far...
protected void gvSignInRegister_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int rowIdx = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvSignInRegister.Rows[rowIdx];
if (row != null && row.RowType == DataControlRowType.DataRow)
{
TextBox tb = (TextBox)row.FindControl("txtReturned");
if (tb != null) tb.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
//I've tried this too but it does not work. Interestingly, it does not crash, so cells[4] must exist!
//row.Cells[4].Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
}
}
}
For some reason the rowIdx is always 0. Why? I thought a row index of 0 meant the header of the gridview control.
I've also tried using the NamingContainer that most other people have suggested in other posts, but that returns a blank (I suspect new?) GridViewRow.
ie
GridViewRow row = (GridViewRow)((GridViewRow)(e.CommandSource).NamingContainer);
UPDATE
I found this, which is exactly the problem I am having, but the solution via the RowEditing still does not find the textbox!
However the RowDataBound() solved it! Read my answer below.
The answer was in getting into the editmode version of the GridView itself and then find the control!
As per this post...
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3"
DataSourceID="sdsSignInRegister" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" GridLines="Vertical" OnRowDataBound="gvSignInRegister_RowDataBound">
<Columns> ...etc...
protected void gvSignInRegister_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
TextBox tb = (TextBox)e.Row.FindControl("txtReturned");
if (tb != null) tb.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
}
}
}
Use Container.DisplayIndex instead of Container.DataItemIndex
But I dont think you will get textBox control if you are placing it in EditItemTemplate
If your expectation is editing operation then please use the below code
HTML
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" OnRowEditing="gvSignInRegister_RowEditing" OnRowCancelingEdit="gvSignInRegister_RowCancelingEdit" OnRowUpdating ="gvSignInRegister_RowUpdating" GridLines="Vertical">
<Columns>
<asp:TemplateField HeaderText="Returned" SortExpression="DateTimeReturned">
<EditItemTemplate>
<asp:TextBox ID="txtReturned" Text='<%#Bind("DateTimeReturned", "{0:dd/MM/yyyy HH:mm}")%>' runat="server"></asp:TextBox>
<asp:ImageButton runat="Server" ID="calImg" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" CausesValidation="False" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Eval( "DateTimeReturned","{0:dd/MM/yyyy HH:mm}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
Code Behind:
protected void gvSignInRegister_RowEditing(object sender, GridViewEditEventArgs e)
{
gvSignInRegister.EditIndex = e.NewEditIndex;
List<QuotationDetail> itemList = (List<QuotationDetail>)ViewState["ItemList"];
gvSignInRegister.DataSource = itemList;
gvSignInRegister.DataBind();
}
protected void gvSignInRegister_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
}
protected void gvSignInRegister_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var txtQty = (TextBox)gvSignInRegister.Rows[e.RowIndex].FindControl("txtQuantity");
decimal qty = 0;
decimal.TryParse(txtQty.Text, out qty);
if (qty < 0)
{
lblErrorSummary.InnerText = "Please provide valid Quantity";
lblErrorSummary.Visible = true;
return;
}
itemList[e.RowIndex].Quantity = qty
ViewState["ItemList"] = itemList;
gvSignInRegister.EditIndex = -1;
gvSignInRegister.DataSource = itemList;
gvSignInRegister.DataBind();
}
Related
I am trying to calculate the sum of the grand total column and showing it to the footer of the gridview, which I am able to achieve it. However I have a condition which makes some rows invisible from the gridview, but it is also summing the value of the rows which are invisible. How to sum the column value only for the rows which are visible?
Below is my gridview:
<asp:GridView ID="GridView9" runat="server" AllowPaging="false" AutoGenerateColumns="False"
ShowFooter="true" BackColor="White" DataKeyNames="ID" BorderColor="#999999" CssClass="tableUserInfo"
GridLines="Vertical" ShowHeaderWhenEmpty="True" PageSize="10" OnRowDataBound="GridView9_RowDataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="SessionId" Visible="true">
<ItemTemplate>
<asp:TextBox ID="txt_GSessionId" runat="server" Text='<%# Eval("SessionId") %>' ReadOnly="true"
Visible="false"></asp:TextBox>
</ItemTemplate>
<HeaderStyle Width="10%" />
<ItemStyle Width="10%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer" Visible="true">
<ItemTemplate>
<asp:Label ID="lblCustomerName" Font-Size="11px" runat="server" Text='<%# Eval("CustomerName") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Width="8%" />
<ItemStyle Width="8%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="G_Total" Visible="true">
<ItemTemplate>
<asp:Label ID="lblGTotal" Font-Size="11px" runat="server" Text='<%# Eval("GTotal","{0:n}") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
<FooterStyle Width="30%" />
<HeaderStyle Width="8%" />
<ItemStyle Width="8%" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="Black" ForeColor="Red" Width="100%" Wrap="false" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
</asp:GridView>
Here is my code behind:
decimal grdTotal;
protected void GridView9_RowDataBound(object sender, GridViewRowEventArgs e)
{
txt_SessionId.Text = ddlSession.SelectedValue;
foreach (GridViewRow row2 in GridView9.Rows)
{
TextBox sid = row2.FindControl("txt_GSessionId") as TextBox;
int a, b;
a = int.Parse(sid.Text);
b = int.Parse(txt_SessionId.Text);
if (a == b)
{
row2.Visible = true;
}
else
{
row2.Visible = false;
}
}
if (e.Row.Visible && e.Row.RowType == DataControlRowType.DataRow)
{
decimal rowTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "GTotal"));
grdTotal = grdTotal + rowTotal;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
Label lbl1 = (Label)e.Row.FindControl("lblLabourTotal");
lbl.Font.Size = 12;
lbl.Text = "Rs. " + grdTotal.ToString("0");
lbl.ForeColor = System.Drawing.Color.White;
}
}
I have been looking all over web and testing what I think would work. I feel close but I guess not close enough. I need help pull the data in. The button click is to submit/insert data into the DB which I have not completed that part. Right now I am working on just getting data from the Gridview and need help.
The Update Button is outside the Gridview. I want end user to complete GridView then click update to submit data from Gridview to database.
Here is ASPX
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="dsSnumbers" OnRowDataBound="GridView1_RowDataBound"
GridLines="Horizontal" BackColor="White" BorderColor="#336666" BorderStyle="Double"
BorderWidth="3px">
<Columns>
<asp:TemplateField HeaderText="SerialNumber">
<ItemTemplate>
<asp:TextBox ID="TextBox1" BackColor="BurlyWood" runat="server" Text='<%# Eval("SerialNumber") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="DdStatus" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dept">
<ItemTemplate>
<asp:DropDownList ID="DdDept" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" RepeatLayout="Flow" RepeatDirection="Horizontal"
runat="server">
<asp:ListItem Text="Modify?" Value="1">
</asp:ListItem>
</asp:CheckBoxList>
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
<%-- <EmptyDataTemplate></EmptyDataTemplate>--%>
</asp:GridView>
And here is the .CS side
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
int RI = g1.RowIndex;
//SqlConnection con = new SqlConnection(connStr);
TextBox test = (TextBox)g1.Cells[0].FindControl("TextBox1");
TextBox test1 = (TextBox)g1.Cells[1].FindControl("TextBox1");
GridViewRow Grow = (GridViewRow)g1.NamingContainer;
TextBox txtledName = (TextBox)Grow.FindControl("TextBox1");
DropDownList testdd1 = (DropDownList)g1.Cells[0].FindControl("DdStatus");
DropDownList testdd2 = (DropDownList)g1.Cells[1].FindControl("DdStatus");
string test1324 = g1.Cells[1].Text;
string test2 = g1.Cells[2].Text;
string test3 = g1.Cells[3].Text;
}
}
Update:
When I run the below I can read the button click whether it is checked or not. However the textbox and dropdown still do nothing. I show ONLY rindex is pulling values. None of the others.
foreach (GridViewRow row in GridView1.Rows)
{
int rindex = row.DataItemIndex;
//string Test = ((TextBox)(row.Cells[0].Controls[0])).Text;
TextBox IDNum = (TextBox)row.FindControl("TextBox1");
string textBox1 = ((TextBox)row.FindControl("TextBox1")).Text;
string ddl1 = ((DropDownList)row.FindControl("DdStatus")).SelectedValue;
string ddl2 = ((DropDownList)row.FindControl("DdDept")).SelectedValue;
int ddl1231 = ((DropDownList)row.FindControl("DdStatus")).SelectedIndex;
int ddl1232 = ((DropDownList)row.FindControl("DdDept")).SelectedIndex;
I have a gridview in which I have a column name "Selection". I want whenver a admin selects Not Selected option the respective user should get an email on his ID that he has been rejected. Please see the gridview code for your reference:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true" Width="920"
PageSize="5" OnPageIndexChanging="gv_Applicants_PageIndexChanging" OnRowCommand="gv_Applicants_RowCommand"
EmptyDataText="No Applicants Found."
AllowSorting="true"
OnSorting="gv_Applicants_Sorting"
OnRowDataBound="gv_Applicants_RowDataBound" RowStyle-CssClass="a12" AlternatingRowStyle-CssClass="a22" ForeColor="#333333" GridLines="None" CssClass="table_box" HeaderStyle-Height="35px">
<AlternatingRowStyle BackColor="#F0F0F0" />
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="First Name" HeaderStyle-Width="84" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" HeaderStyle-Width="106" />
<asp:BoundField DataField="ContactNumber" HeaderText="Contact" HeaderStyle-Width="98" />
<asp:BoundField DataField="Email" HeaderText="Email" HeaderStyle-Width="150" />
<asp:TemplateField HeaderText="Position" SortExpression="Position" HeaderStyle-Width="107">
<ItemTemplate>
<%# Eval("Job.Position") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location" SortExpression="Location" HeaderStyle-Width="100">
<ItemTemplate>
<%# Eval("Job.Location") %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="AppliedDate" DataFormatString="{0:MMMM dd, yyyy}" HeaderText="Date of Application" ReadOnly="true" HeaderStyle-Width="121" />
<asp:TemplateField HeaderText="Action" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID='lnkView' CommandName='v' Text='View' runat='server' CommandArgument='<%# Eval("ApplicantId") %>'></asp:LinkButton>
|
<asp:LinkButton ID='lnkdel' CommandName='d' Text='Delete' runat='server' CommandArgument='<%# Eval("ApplicantId") %>' OnClientClick="return confirm('Are you sure to delete?');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Selection">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Visible="true" />
<asp:DropDownList ID="ddlCountries" runat="server">
<asp:ListItem Text="None" Value="1"></asp:ListItem>
<asp:ListItem Text="Selected" Value="2"></asp:ListItem>
<asp:ListItem Text="Not Selected" Value="3"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#D8DADA" Font-Bold="True" />
<HeaderStyle BackColor="#D8DADA" Font-Bold="True" />
<PagerStyle BackColor="#D8DADA" HorizontalAlign="Center" />
<RowStyle BackColor="white" BorderStyle="Solid" BorderColor="#a8a8a8" BorderWidth="1px" Height="35" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
Eidted code:-
private void SendMail()
{
StringBuilder sbuilder = new StringBuilder();
sbuilder.Append("<div>");
sbuilder.Append("<p>Thanks for applying at RBL. You have been rejected</p>");
sbuilder.Append("</div>");
string str = sbuilder.ToString();
string ccEmail = "";
Common objCom = new Common();
string toId = ConfigurationManager.AppSettings["ddlEmail"].ToString();
objCom.SendEMail(toId, "Rejection Mail", sbuilder.ToString(), ccEmail, false, "");
}
protected void ddlSelection_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.Parent.Parent;
if (ddl.SelectedValue == "Not Selected")
{
SendMail();
}
}
Try this,
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("ddlCountries") as DropDownList;
if(ddl != null)
{
ddl.SelectedIndexChanged += new EventHandler(ddlCountries_SelectedIndexChanged);
}
}
}
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedValue = ((DropDownList)sender).SelectedValue;
if(selectedValue== "Not Selected")
{
// Write code here for sending mail
}
}
Here i need to get the DataKeyNames on which row i click(in side tools column image button click)
but when i click on the imagebutton(pencil) it show the following error
my C# codes is
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
ImageButton btnedit = sender as ImageButton;
GridViewRow gvrow = btnedit.NamingContainer as GridViewRow;
int sid = Convert.ToInt32(GridView1.DataKeys[gvrow.RowIndex].Value);
Response.Write(sid);
}
else if (e.CommandName == "Delete")
{
}
}
my Gridview source codes
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" DataKeyNames="StdId" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" EnableModelValidation="True" GridLines="None">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate><%#Eval("Name") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate><%#Eval("Email") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile">
<ItemTemplate><%#Eval("Mobile") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate><%#Eval("City") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tools">
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" runat="server" CommandArgument="ImageButton" CommandName="Edit" ImageUrl="~/pencil.png" ToolTip="Click To Edit" AlternateText="Click To Edit"/>
<asp:ImageButton ID="imgbtnDelete" runat="server" CommandName="Delete" ImageUrl="~/cross.png" ToolTip="Click To Dletee" AlternateText="Click To Dletee"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
</asp:GridView>
please help me how to get the DatakeyName
First you need to add an OnRowCreated event to your gridview
OnRowCreated="GridView1_RowCreated"
An in .cs file add this ( set the Rowindex value in CommandArgument so you can get this on RoeCommand)
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton imgbtnEdit= (ImageButton)e.Row.FindControl("lnkUrlID");
imgbtnEdit.CommandArgument = e.Row.RowIndex.ToString();
ImageButton imgbtnDelete= (ImageButton )e.Row.FindControl("lnkExtend");
imgbtnDelete.CommandArgument = e.Row.RowIndex.ToString();
}
}
Now at your GridView1_RowCommand try this
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int sid = Convert.ToInt32(GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
}
}
My gridview is like this but I am getting error when I select view button to find primary key value column on selected index changed. Please help me to solve the issue.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns >
<asp:TemplateField >
<ItemTemplate >
<asp:Button ID="btnViewComments" Text ="View Comments" runat ="server" CommandName ="select" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField ="forumId" Visible ="false" />
<%--<asp:CommandField ButtonType ="Button" ShowSelectButton ="true" SelectText ="View Comments"/>--%>
<asp:TemplateField HeaderText ="Question">
<ItemTemplate >
<asp:TextBox ID ="txtQuestion" Text ='<%#Eval("question")%>' runat ="server" TextMode ="MultiLine" Height="100" Width ="350"></asp:TextBox>
<%-- <%#Eval("question")%>--%>
</ItemTemplate>
<%--<EditItemTemplate >
<asp:TextBox ID ="txtQuestion" Text ='<%#Eval("question")%>' runat ="server" TextMode ="MultiLine" ></asp:TextBox>
</EditItemTemplate>--%>
</asp:TemplateField>
<asp:TemplateField HeaderText="Poster Name">
<ItemTemplate >
<%#Eval("posterName") %>
</ItemTemplate>
<EditItemTemplate >
<asp:Label ID ="lblPosterName" Text ='<%#Eval("posterName") %>' runat ="server" ></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate >
<%#Eval("dateTim") %>
</ItemTemplate>
<EditItemTemplate >
<asp:Label ID ="lblDateTime" Text ='<%#Eval("dateTim") %>' runat ="server" ></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
my code is.....
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
Int64 forumId = (Int64)GridView1.SelectedValue;
Session["forumId"] = forumId;
Response.Redirect("Thread.aspx");
}
catch (Exception)
{
throw;
}
}
First you have to define field name in grid view declaration that which field you want to make datakey. for example if you want "forumId" datakey.than
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
DataKeyNames="forumId">
and than you can access in this way
int intforumid = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
Int64 forumId = Convert.ToInt64(GridView1.SelectedRow.Cells[1].Text);
Session["forumId"] = forumId;
Response.Redirect("Thread.aspx");
}
catch (Exception)
{
throw;
}
}
Looks like you just need to set DataKeyNames property to forumId like;
<asp:GridView DataKeyNames = "forumId" ...
you can set DataKeyNames as forumId like below
<asp:GridView ID="GridView1" runat="server" DataKeyNames = "forumId" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
Since you haven't give any data key names in current solution GridView1.SelectedValue will not contain the value you expected
You would need to specify the unique column name in the gridview to be set under the Datakey tab.
From there, you would need to invoke the _selectedIndexChanged method on the behind page code.
If you are not using gridview select event in your page.cs code then you just remove OnSelectedIndexChanged="GridView1_SelectedIndexChanged" from the aspx code of page of gridview.