When using a GridView, SelectedIndex is always 0 when using custom select button - asp.net

When clicking the select button in gvSquid2, x gets a valid and correct value. When clicking the select button in gvSquid, I get an ArgumentOutOfRange Exception because gv.SelectedIndex=0. Additionally, gv.SelectedDataKey is null. How do I get the DataKey information? Putting it in a column is not acceptable, as it must be hidden from the user. Hiding the column is useless, because during DataBind(), the value is discarded. I ripped this example from Microsoft's website. What am I missing?
<asp:gridview ID="gvSquid2" DataSourceID="dsComments" AutoGenerateColumns="false" AutoGenerateSelectButton="true" DataKeyNames="ID" OnSelectedIndexChanged="gvSquid_SelectedIndexChanged" runat="server" EnableViewState="false">
<Columns>
<asp:BoundField DataField="Date" ReadOnly="true" HeaderText="Date" SortExpression="Date" />
<asp:BoundField DataField="Comment" ReadOnly="true" HeaderText="Comment" SortExpression="Comment" />
<asp:BoundField DataField="Username" ReadOnly="true" HeaderText="User" SortExpression="Username" />
</Columns>
</asp:gridview>
<asp:gridview ID="gvSquid" DataSourceID="dsComments" AutoGenerateColumns="false" DataKeyNames="ID" OnSelectedIndexChanged="gvSquid_SelectedIndexChanged" runat="server" EnableViewState="false">
<Columns>
<asp:CommandField ButtonType="Image" HeaderText="Select" ShowSelectButton="true" SelectImageUrl="~/includes/RedX.jpg" />
<asp:BoundField DataField="Date" ReadOnly="true" HeaderText="Date" SortExpression="Date" />
<asp:BoundField DataField="Comment" ReadOnly="true" HeaderText="Comment" SortExpression="Comment" />
<asp:BoundField DataField="Username" ReadOnly="true" HeaderText="User" SortExpression="Username" />
</Columns>
</asp:gridview>
protected void gvSquid_SelectedIndexChanged(object sender, EventArgs e) {
string x;
x = gvSquid.DataKeys[gvSquid.SelectedIndex].Value.ToString();
}

Try using the SelectedRow of the grid view to get to the RowIndex, like this:
protected void gvSquid_SelectedIndexChanged(object sender, EventArgs e)
{
string x;
GridViewRow theGridViewRow = gvSquid.SelectedRow;
x = gvSquid.DataKeys[theGridViewRow.RowIndex].Value.ToString();
}

I figured it out. EnableViewState="true" has to be set. Once I changed that, suddenly the DataKeys appeared.
This question helped.

Related

Image on image button not displaying when changing it dynamically based on the value of a cell in Gridview

I am trying to change the image displayed on the image button based on the value of a cell on a GridView . I tried the following :
<asp:GridView ID="grd_UserDetails" runat="server" AllowPaging="True" AutoGenerateColumns="False"
GridLines="None" Width="600px" CellPadding="4" ForeColor="#333333" OnPageIndexChanging="grd_UserDetails_PageIndexChanging" OnSelectedIndexChanged="grd_UserDetails_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="userId" HeaderText="UserId" ><ItemStyle HorizontalAlign="Center" /></asp:BoundField>
<asp:BoundField DataField="password" HeaderText="Password" ><ItemStyle HorizontalAlign="Center" /></asp:BoundField>
<asp:BoundField DataField="username" HeaderText="UserName" ><ItemStyle HorizontalAlign="Center" /></asp:BoundField>
<asp:BoundField DataField="email" HeaderText="Email Id" ></asp:BoundField>
<asp:BoundField DataField="status" HeaderText="Status" SortExpression="Active" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="img_user" runat="server" CommandName="Select"
ImageUrl='<%# Eval("status") %>' Width="20px" Height="20px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
codebehind :
protected void grd_UserDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton img = (ImageButton)e.Row.FindControl("img_user");
if (e.Row.Cells[4].Text == "Active")
{
img.ImageUrl = "~/images/active.png ";
}
else
{
img.ImageUrl = "~/images/inactive.png ";
}
}
}
But the image button is not displaying any image .How do i fix this. My images seem to be placed correctly in the root .
Remove ImageUrl='<%# Eval("status") %>' in aspx file.
In aspx.cs file, please try as below.
(I assume gridview cell[4]'s data filed name is "Status").
ImageButton img = (ImageButton)e.Row.FindControl("img_user");
string status = (string)DataBinder.Eval(e.Row.DataItem, "Status");
img.ImageUrl = status == "Active" ? "~/images/active.png" : "~/images/inactive.png ";

Adding a new column with buttons in gridview and binding data to it

I have added a button for Print in my gridview table as follows
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource2"
onselectedindexchanged="GridView1_SelectedIndexChanged" Width="522px">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Story_number" HeaderText="Story_number"
SortExpression="Story_number" />
<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
<asp:BoundField DataField="Memory_card" HeaderText="Memory_card"
SortExpression="Memory_card" />
<asp:BoundField DataField="Story_Name" HeaderText="Story_Name"
SortExpression="Story_Name" />
<asp:ButtonField ButtonType="Button" Text="print" />
</Columns>
</asp:GridView>
Please help me with the c# code for this button. When the button is pressed I need it to redirect to a page (print.aspx). I have been trying the following code but it does not work .Thanks in advance for your help.
Session["id"] = GridView1.SelectedRow.Cells[0].Text;
Response.Redirect("Print.aspx");
Instead of buttonField, use template field
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ButtonPrint" runat="server" CssClass="yourCssClassIsNeedIt" OnClick="printRegFunction"
CommandArgument='<%# Bind("id") %>' ImageUrl="images/button.png"/>
</ItemTemplate>
</asp:TemplateField>
your server code or behind code here:
protected void printRegFunction(object sender, ImageClickEventArgs e)
{
Session["id"] = ((ImageButton)sender).CommandArgument;
Response.Redirect("Print.aspx");
}

Getting data from gridView

I have a gridView . And In code Behind I want to get Id and a Name
<asp:GridView ID="GridViewCategory" runat="server"
OnSelectedIndexChanged="GridViewCategory_SelectedIndexChanged"
OnPageIndexChanging="GridViewCategory_PageIndexChanging"
AllowPaging="True" DataKeyNames="Id"
CellPadding="4" ForeColor="#333333" GridLines="None"
>
<Columns>
<asp:BoundField DataField="Id" HeaderText="Идент. номер" ItemStyle-Wrap="false" ItemStyle-Width="20%" />
<asp:BoundField DataField="Name" HeaderText="ALl name For" ItemStyle-Wrap="false" ItemStyle-Width="60%" />
<asp:CommandField SelectText="Избери" ShowSelectButton="True" />
</Columns>
I get Id by this:
protected void GridViewCategory_SelectedIndexChanged(object sender, EventArgs e)
{
int abv = Convert.ToInt32(GridViewCategory.SelectedValue);
//Label labelName = (Label)GridViewCategory.SelectedRow.FindControl("Name"); this is not working I think because it is BoundField And rows don't have Id only DataField
}
but How to get name which is this Id
You could add Name as another datakeyname
<asp:GridView ID="GridViewCategory" runat="server"
OnSelectedIndexChanged="GridViewCategory_SelectedIndexChanged"
OnPageIndexChanging="GridViewCategory_PageIndexChanging"
AllowPaging="True" DataKeyNames="Id, Name"
CellPadding="4" ForeColor="#333333" GridLines="None"
>
<Columns>
<asp:BoundField DataField="Id" HeaderText="Идент. номер" ItemStyle-Wrap="false" ItemStyle-Width="20%" />
<asp:BoundField DataField="Name" HeaderText="ALl name For" ItemStyle-Wrap="false" ItemStyle-Width="60%" />
<asp:CommandField SelectText="Избери" ShowSelectButton="True" />
</Columns>
Then in your code behind:
protected void GridViewCategory_SelectedIndexChanged(object sender, EventArgs e)
{
int index = GridViewCategory.SelectedIndex;
int abv = Convert.ToInt32(this.GridViewCategory.DataKeys[index]["Id"]);
string name = this.GridViewCategory.DataKeys[index]["Name"].ToString();
}
Hope this helps

Row command event of gridview is not firing for radiobuttinlist in asp.net

I have rdiobutton list in ItemTemplet field of gridview which is set ispostback=true but still radiobutton list is not firing row_command event for gridview.If I do same for button then it works fine. I have written code to bind the grid in (!IspostBack) but still the problem is
there..How can I get the rid out of these.
This the code for my Grid.
<asp:GridView ID="grdSalesPerson" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" OnRowCommand="grdSalesPerson_RowCommand">
<Columns>
<asp:BoundField DataField="SalesPersonID" HeaderText="SalesPersonID" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="UserName" HeaderText="User Name" />
<asp:BoundField DataField="StateName" HeaderText="State Name" />
<asp:BoundField DataField="CityName" HeaderText="City Name" />
<asp:TemplateField HeaderText="Is Active">
<ItemTemplate>
<asp:RadioButtonList ID="rbActive" runat="server" CommandName="IsAct" AutoPostBack="true">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is the code for Row_Command Event
protected void grdSalesPerson_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "IsAct")
{
// GridViewRow row = (GridViewRow) (((Button)grdSalesPerson.FindControl("btnIsActive")).NamingContainer);
GridViewRow row = (GridViewRow)(((RadioButton)e.CommandSource).NamingContainer);
int i = Convert.ToInt32(row.Cells[0].Text);
}
}

how to refresh the gridview after it filters (Dynamic) using LinqDataSource?

<asp:GridView ID="GridView2" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataSourceID="LinqDataSource1">
<Columns>
<asp:BoundField DataField="UserName" HeaderText="User Name" ReadOnly="True"
SortExpression="UserName" />
<asp:BoundField DataField="FullName" HeaderText="Full Name" ReadOnly="True"
SortExpression="FullName" />
<asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True"
SortExpression="Email" />
<asp:BoundField DataField="LastLoginDate" HeaderText="Last Login" ReadOnly="True"
SortExpression="LastLoginDate" DataFormatString="{0:dd MMMM yyyy}"/>
<asp:HyperLinkField Text="Edit" DataNavigateUrlFields="UserId" DataNavigateUrlFormatString="~/Pages/UsersMaintenance/CreateEditUser.aspx?UserId={0}" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="MyDataContextDataContext" onselecting="LinqDataSource_Selecting">
<WhereParameters>
<asp:Parameter Name="Subject" />
</WhereParameters>
</asp:LinqDataSource>
public void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
this.LinqDataSource1.WhereParameters["Subject"].DefaultValue = this.txtSubject.Text;
e.Result = reporterRepo.GetInquiries();
Try using this, or modify it till it works. If I'm correct I did something like this before:
public void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
this.LinqDataSource1.WhereParameters["Subject"].DefaultValue = this.txtSubject.Text;
GridView2.DataBind();
e.Cancel = true;
}
my gridview was in updatepanel thats why it was not refreshing the gridview
<asp:UpdatePanel....

Resources