Select a row without set AutoGenerateSelectButton to true - asp.net

How to select a row without set AutoGenerateSelectButton to true and check selectedIndex in GridView_SelectedIndexChanged?
How to recognize that user select specific field on table (for example selected row2,col3)

This is an average gridview with no select button. The RowDataBound method makes your grid highlightable. You can check if a certain column was selected possibly with if conditions in your SelectedIndexChanged method as that will tell you what row was selected and then you can get a value from a specific column based on the order your columns were made as shown below. This wont show exactly where they clicked x and y but should head you in the right direction I think. This will however get column data based on what row was highlighted and clicked on with a post back of course.
<asp:GridView ID="PropertyGridView" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="PropertyGridView_SelectedIndexChanged" OnRowDataBound="PropertyGridView_RowDataBound">
<RowStyle HorizontalAlign="Left" />
<EmptyDataTemplate>
<div>
<asp:Label runat="server" ID="EtLbl" Text="No properties were found."</asp:Label>
</div>
</EmptyDataTemplate>
<Columns>
<asp:BoundField DataField="Name" HeaderText="User Name" Width="20%" /> </asp:BoundField>
<asp:BoundField DataField="Age" HeaderText="User Age" Width="20%" /> </asp:BoundField>
<asp:BoundField DataField="Height" HeaderText="User Height" Width="20%" /> </asp:BoundField>
</Columns>
</asp:GridView>
public void PropertyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItemIndex == -1)
return;
e.Row.Attributes.Add("onMouseOver", "this.style.cursor='hand';");
e.Row.Attributes.Add("onclick", this.GetPostBackClientEvent(PropertyGridView,"Select$" + e.Row.RowIndex.ToString()));
}
public void PropertyGridView_SelectedIndexChanged(object sender, EventArgs e)
{
string Name = PropertyGridView.SelectedRow.Cells[0].Text;
string Age= PropertyGridView.SelectedRow.Cells[1].Text;
string Height PropertyGridView.SelectedRow.Cells[2].Text;
if( Height != null)
{
// The user selected a row and this Column ( Height has data )
}
}

Add a column with a button (using a template field) and set the CommandName to "Select". That should work.

Related

How to use checkbox check change without refreshing page in ASP.NET

I have two checkboxes in a gridview. The scenario is this: only one of these checkboxes can be chosen or none of them.
My problem is that when my gridview got too big, every time I check or uncheck each row the page refresh that is because of I set auto post back = true! What should I do to avoid this refreshing and the scenario works except UpdatePanel!
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" BackColor="White">
<Columns>
<asp:TemplateField HeaderText="morakhasi" ItemStyle-Width="80">
<ItemTemplate><asp:CheckBox ID="chkboxMorakhasi" OnCheckedChanged="chkboxMorakhasi_CheckedChanged" runat="server" AutoPostBack="true"/>
</ItemTemplate>
<HeaderStyle Font-Size="16px" Width="80px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="taiid" ItemStyle-Width="80">
<ItemTemplate><asp:CheckBox ID="chkboxTaiid" OnCheckedChanged="chkboxTaiid_CheckedChanged" runat="server" Checked="True" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</gridview>
Code behind:
protected void chkboxTaiid_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow gr in GridView2.Rows)
{
GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
int index = row.RowIndex;
CheckBox cb1 = (CheckBox)GridView2.Rows[index].FindControl("chkboxTaiid");
CheckBox cb2 = (CheckBox)GridView2.Rows[index].FindControl("chkboxMorakhasi");
cb2.Checked = Convert.ToBoolean(0);
}
}
protected void chkboxMorakhasi_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow gr in GridView2.Rows)
{
GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
int index = row.RowIndex;
CheckBox cb1 = (CheckBox)GridView2.Rows[index].FindControl("chkboxTaiid");
CheckBox cb2 = (CheckBox)GridView2.Rows[index].FindControl("chkboxMorakhasi");
cb1.Checked = Convert.ToBoolean(0);
}
}
You should use UpdatePanel control to do this
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:CheckBox
OnCheckedChanged="chkCompany_OnCheckedChanged"
AutoPostBack="True" CssClass="chkCompany"
ClientIDMode="Static" ID="chkCompany" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
Well, first up, when you say the grid is large? Well, how large? 20 rows or 2000 rows?
When Google, or even Microsoft asks interview questions? A good number of these questions are of a how high, how far, how big type of questions. And the reason for that is simple:
They want to determine if you have a mind can is able to evaluate scope and scale of problems that you have to solve. (so, they might ask how would you move Mount Fuji?)
anyway:
I can't image the grid has what, 30 rows on a page? (why so many and why so large??).
I mean, if you have more, then we need to know how many more?
However, lets get the first problem solved. (the check box issue), and then we can try and deal with the re-plot/refresh issue.
Ok, so say we have this grid markup - grid + 2 check boxes
<asp:GridView ID="GVHotels" runat="server" class="table" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" HeaderStyle-Width="200" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Choice 1" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chk1" runat="server"
OnCheckedChanged="chk1_CheckedChanged" AutoPostBack="true"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Choice 2" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chk2" runat="server"
OnCheckedChanged="chk2_CheckedChanged" AutoPostBack="true"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code to load the grid is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST3))
{
using (SqlCommand cmdSQL =
new SqlCommand("SELECT * from tblHotels ORDER BY HotelName ", con))
{
con.Open();
GVHotels.DataSource = cmdSQL.ExecuteReader();
GVHotels.DataBind();
}
}
}
And now we have this:
And our two check box changed events are this:
protected void chk1_CheckedChanged(object sender, EventArgs e)
{
CheckBox ck = (CheckBox)sender;
GridViewRow gRow = (GridViewRow)ck.Parent.Parent;
if (ck.Checked)
// uncheck the other box
((CheckBox)gRow.FindControl("chk2")).Checked = false;
}
protected void chk2_CheckedChanged(object sender, EventArgs e)
{
CheckBox ck = (CheckBox)sender;
GridViewRow gRow = (GridViewRow)ck.Parent.Parent;
if (ck.Checked)
// uncheck the other box
((CheckBox)gRow.FindControl("chk1")).Checked = false;
}
Ok, so we are done.
the next issue is performance? A grid of say 20-40 rows on the form should work ok.
I think just drop a update panel around the grid, and you done.
So, we drop in script manager, and then this:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
-- above grid goes here!!!
</ContentTemplate>
</asp:UpdatePanel>
Now, I just tested the above with 50 rows on the screen. I can't see or feel, or notice ANY replot delay, and in fact the check box reacts as fast as my mouse click. In fact the check box status changes quite much as fast as the mouse click, and in fact quite much at the same time I hear the click.
So, above is the layout for the code you require here. If there is some "slow" ness, or delay, or your data set is larger, then perhaps some kind of data pager should be introduced. On the other hand, you not shared, or noted how many rows this grid is displaying on the screen. And without that information, we shooting in the dark here as to what possible solutions(s) exist (or that what you have is a very bad idea).

ASP.NET Gridview Selected Index Changed not firing

This has been asked quite a few times, but still.
In GridView is defined event OnSelectedIndexChanged. My expectation is, that if I click on a row in gridview, the event will be fired. I managed to do the same with image buttons, but I want the entire row to be clickable.
<asp:GridView runat="server" ID="gameGrid" PageSize="20" PagerSettings-Mode="NextPreviousFirstLast"
OnRowDataBound="GameGrid_RowDataBound" OnPageIndexChanging="GameGrid_PageIndexChanging"
AutoGenerateColumns="false" CssClass="table table-hover table-striped" AllowPaging="True"
AllowSorting="True" ShowHeaderWhenEmpty="True" OnSelectedIndexChanged="gameGrid_SelectedIndexChanged">
<Columns>
<asp:BoundField HeaderText="Game Id" DataField="ID_Game" SortExpression="ID_Game" />
<asp:BoundField HeaderText="Player" DataField="Email" SortExpression="Email" />
<asp:BoundField HeaderText="Finshed" SortExpression="Finished" />
<asp:BoundField HeaderText="Started At" SortExpression="CreateDate" />
<asp:BoundField HeaderText="Last Updated At" SortExpression="LastUpdate" />
</Columns>
</asp:GridView>
I was assuming that if I define an EventHandler in CodeBehind, it will be fired.
protected void gameGrid_SelectedIndexChanged(object sender, EventArgs e)
{
int i = 0;
}
Why is this event not firing?
I would like to redirect the user on a different page with an ID parameter in URL. Should I do something different?
First, set the AutoGenerateSelectButton property to true in the GridView. This will generate a LinkButton. Now in the RowDataBound event do the following.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//find the select button in the row (in this case the first control in the first cell)
LinkButton lb = e.Row.Cells[0].Controls[0] as LinkButton;
//hide the button, but it still needs to be on the page
lb.Attributes.Add("style", "display:none");
//add the click event to the gridview row
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackClientHyperlink((GridView)sender, "Select$" + e.Row.RowIndex));
}
}
You could add the OnClick event to the row without showing the SelectButton, but then you would to turn off EnableEventValidation as seen here How to create a gridview row clickable?

How to Sort in GridView

Here is my GV.
<asp:GridView ID="Grid1" runat="server" AutoGenerateColumns="false"
AllowPaging="True" OnPageIndexChanging="Grid1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="One" HeaderText="One" />
<asp:BoundField DataField="Two" HeaderText="Two" />
<asp:BoundField DataField="Three" HeaderText="Three" />
</Columns>
</asp:GridView>
I'm populating the GV with a Stored Procedure.
table = PublicClass.Sql_GetTable("usp_GetReportGridView", "NCIU");
Grid1.DataSource = table;
Grid1.DataBind();
How can I sort using the column headers?
First you need to enable AllowSorting property to be true. When enabled, the grid renders LinkButton controls in the header for each column. When the button is clicked, the grid's SortCommand event is thrown. It's up to the you to handle this event in the code. Because DataGrid always displays the data in the same order it occurs in the data source, the typical logic sorts the data source, and then rebinds the data to the grid.look at code below:
//AllowSorting="True"
//OnSorting="GridView2_Sorting"
//SortExpression="name"
protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
//to check whether to display in ascending order or descending order
if (e.SortExpression.Trim() == this.SortField)
this.SortDirection = (this.SortDirection == "D" ? "A" : "D");
else
this.SortDirection = "A";
this.SortField = e.SortExpression;
TempTable();
}

How to get the non visible gridview cell value in ASP.net?

I have a grid like below.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" s
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:ButtonField DataTextField="Name" HeaderText="Name" />
<asp:BoundField DataField="ArrDate" DataFormatString="{0:MM/dd/yyyy}"
HeaderText="Arr Date" />
<asp:BoundField HeaderText="Dep Date" DataField="DepDate"
DataFormatString="{0:MM/dd/yyyy}" />
<asp:BoundField HeaderText="Mail" DataField="Mail" />
<asp:BoundField HeaderText="Status" DataField="Status" />
<asp:BoundField DataField="ResId" HeaderText="ResId" Visible="False" />
</Columns>
</asp:GridView>
In Code Behind:-
try
{
string text = GridView1.Rows[2].Cells[5].Text;
ScriptManager.RegisterStartupScript(this, GetType(), "Message", "alert('ResId = " + text + ".');", true);
}
catch { }
Now the message shows - RegId =.
I can't get the value. So I change the RedId BoundField as vissible. Now I got the Value.
that is RegId =6.
I have two issue now -
1) How to get the RegId value in Non Visible Column.
2) How I find the Row value which i click... bzs the only i can change the ROWVALUE in code..
string text = GridView1.Rows[ROWVALUE].Cells[5].Text;
That is certainly not the right way to do it. You might want to look at using DataKeys to achieve this. With current approach, when you add a new column to your grid your code will fail.
Add your RegId column inside DataKeys property on your gridview
Reference your gridview datakey for the current row in codebehind like this
int regId= Convert.ToInt32(YourGridview.DataKeys[rowIndex]["RegId"].ToString());

Unable to access the checkbox for Serverside coding

Below is my gridview ,
<asp:GridView ID="gridview1" AutoGenerateColumns="False" runat="server"
EnableModelValidation="True" >
<Columns>
<asp:CommandField ButtonType="Link" HeaderText="Delete" InsertImageUrl="~/_layouts/images/TBS.WebParts/Button-Delete-icon.png" ShowDeleteButton="true"/>
<asp:BoundField HeaderText ="Size" DataField="FileSize" />
<asp:BoundField HeaderText ="File" DataField="Size" />
<asp:TemplateField HeaderText="SupportIncluded">
<ItemTemplate>
<asp:CheckBox ID="Checkbox1" runat="server" Checked="false" />
</ItemTemplate>
Now on server side i want to check if the checkbox is checked or not on Submit button click event.
private void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValidPost())
{
bool flag = false;
for( int i=0; i < gridview1.Rows.Count ; i++)
{
if(dgdUpload.Rows[i].FindControl("Checkbox1"),CheckBox).Checked) erorr here...I also tried ....if(Checkbox1.checked)...but unable to access Checkbox1..it says it does not exist in the current context....
flag = true;
}
if(flag)
{
}
}
}
You need to access not only the row but also the template field control. Another option is to develop your own recursive version of FindControl that does a search on the whole tree and not just on one level.
Something like:
dgdUpload.Rows[i].Controls[5].FindControl("Checkbox1")
if I counted the columns in your gridview correctly 5 should be the index of the template field.

Resources