Firing GridView SelectedIndexChanged from code behind - c#

I have a gridview with the implementation of SelectedIndexChanged.
<asp:GridView ID="gvCalloutTeam" runat="server" OnRowDataBound="gvCalloutTeam_RowDataBound" OnSelectedIndexChanged="gvCalloutTeam_SelectedIndexChanged"
AutoGenerateColumns="False" EnableViewState="False" BackColor="White" BorderColor="#cccccc" BorderWidth="1px" CellPadding="2"
EmptyDataText="No person found" GridLines="None" Width="100%">
<AlternatingRowStyle BackColor="#ededed" />
<Columns>
.......... List of columns..............
</Columns>
<FooterStyle BackColor="#cccccc" ForeColor="Black" />
<HeaderStyle BackColor="#6699cc" Font-Bold="True" ForeColor="White" BorderColor="#cccccc" BorderWidth="1px" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#fefefe" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
I have a check box on the page and CheckedChanged Event implemented on that.
<asp:CheckBox ID="cbTakeOutOrder" runat="server" Text="Take out of order" OnCheckedChanged="cbTakeOutOrder_CheckedChanged" AutoPostBack="true" />
I'm trying to set SelectedIndex of GridView from this event.
protected void cbTakeOutOrder_CheckedChanged(object sender, EventArgs e)
{
if (!cbTakeOutOrder.Checked && gvCalloutTeam.Rows.Count > 0)
gvCalloutTeam.SelectedIndex = 0;
}
But it doesn't fire the SelectedIndexChanged event of GridView. If I select the row on UI, it fires but if I change Index in code, it doesn't fire the event. Is there a way to invoke the event, after changing SelectedIndex in code behind?
protected void gvCalloutTeam_SelectedIndexChanged(object sender, EventArgs e)
{
//////////////////my logic
}

If you are on .net 4.5, you can call SelectRow method on the GridView:
protected void cbTakeOutOrder_CheckedChanged(object sender, EventArgs e)
{
if (!cbTakeOutOrder.Checked && gvCalloutTeam.Rows.Count > 0)
gvCalloutTeam.SelectRow(0);
}

Related

Can't get value from gridview button field

I am facing difficulties when trying to get values from a cell in a gridview. Whenever I ask for the value it goes to NullExcaption, so I asked if the row itself is null, and it is. Here is the ASP code:
<asp:SqlDataSource ID="SqlDataSourceFlats" runat="server" ConnectionString="<%$ ConnectionStrings:EflatsConnectionString %>" SelectCommand="SELECT [Rent], [Address], [FlatId] FROM [Flat_Main]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" onrowcommand="GridView1_RowCommand" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="FlatId" DataSourceID="SqlDataSourceFlats" ForeColor="#333333" GridLines="None" Width="100%" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="FlatId" HeaderText="FlatId" InsertVisible="False" ReadOnly="True" SortExpression="FlatId" />
<asp:BoundField DataField="Rent" HeaderText="Rent" SortExpression="Rent" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address">
<ControlStyle Width="60%" />
</asp:BoundField>
<asp:ButtonField Text="Add" CommandName="Apply" ButtonType="Button" />
<asp:ButtonField Text="Remove" ButtonType="Button" />
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
And the button code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Apply")
{
// string c = GridView1.Rows[e.NewEditIndex].Cells[2].Text;
// Response.Write(GridView1.SelectedRow.Cells[2].Text);
if (GridView1.SelectedRow == null)
{
Response.Write("Gridview is failing me :(");
}
// string celltext = this.GridView1.SelectedRow.Cells[2].Text;
// Response.Write(celltext);
}
}
Basically I want to click the button and get the FlatId value from the selected row.
The OnRowCommand event seems to have few mistakes.
1.) GridView1.SelectedRow::
you haven't actually selected any row, therefore this will always be null
2.) GridView1.Rows[e.NewEditIndex]::
Again, you are NOT editing any row, so what do you expect the value will be for e.NewEditIndex ?
How to Handle ButtonField events in the GridView control
Set the button's CommandName property to a string that identifies its function, such as "Select" , "Edit" etc...
To determine the index of the record, the RowIndex, use the CommandArgument property of the event argument that is passed to the command event for the data-bound control. The ButtonField class automatically populates the CommandArgument property with the appropriate row-index value.
Below is an example for selecting a record and Handling the OnRowCommand event:
Markup:
<columns>
<asp:buttonfield buttontype="Button" commandname="Select"
headertext="Select This Record" text="Select"/>
</columns>
and the OnRowCommand event:
void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Select")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int _rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = CustomersGridView.Rows[_rowIndex];
string cellText = selectedRow.Cells[2].Text;
}
}

By using below code how can i delete image from folder in asp .net

<asp:GridView ID="gvDisplayImages" runat="server" BackColor="#CCCCCC"
BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4"
CellSpacing="2" ForeColor="Black" AutoGenerateColumns="false" DataKeyNames="intId"
onrowdeleting="gvDisplayImages_RowDeleting"
onselectedindexchanged="gvDisplayImages_SelectedIndexChanged">
<Columns>
<asp:CommandField SelectText="Delete" ShowDeleteButton="true" />
<asp:BoundField DataField="varImageName" HeaderText="ImageName"
SortExpression="varImageName" />
<asp:TemplateField HeaderText="Preview Image">
<ItemTemplate>
<asp:Image ID ="Img1" runat="server" Height="150" Width="200" ImageUrl='<%#ResolveUrl ("~/" + Eval("varImagePath")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
code for cs page
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
public void BindData()
{
gvDisplayImages.DataSource = bcObj.DisplayImages();
gvDisplayImages.DataBind();
}
protected void gvDisplayImages_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int intId = Convert.ToInt32(gvDisplayImages.DataKeys[e.RowIndex].Value.ToString());
bcObj.DeleteImage(intId);
BindData();
string filename = Convert.ToString(gvDisplayImages.Rows[e.RowIndex].FindControl("Img1") as Image);
string filepath = "\\Image\\" + filename;
FileInfo file = new FileInfo(filepath);
if (file.Exists)
{
file.Delete();
}
}
Here I am using 3 tier architecture in asp .net By using above code while click delete button in gridview, images are deleted from database successfully. Now please tell me how should I delete image from folder where all images are stored.
Need to use ImageUrl in your code.
like this
string filename = ((Image)(gvDisplayImages.Rows[e.RowIndex].FindControl("Img1"))).ImageUrl;

Problems getting the control from GridViewRow

I have a gridview which is created on a button click. It has some checkboxes so the user can adjust the CRUD access rights for certain pages and then save all rows.
I have another button to save the rows where I loop through, getting the rowID and the access rights to save.
I am having a problem when saving, it can't find the control in the row and when it gets to ID= I get a object referenced exception. If I do the checkbox assignments first, I get the error on the C= part.
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow r in gvRights.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
int ID;
ID = Convert.ToUInt16(r.Cells[0].ToString());
bool C, R, U, D;
CheckBox chkC = r.FindControl("chkC") as CheckBox;
C = chkC.Checked;
CheckBox chkR = r.FindControl("chkR") as CheckBox;
R = chkR.Checked;
CheckBox chkU = r.FindControl("chkU") as CheckBox;
U = chkU.Checked;
CheckBox chkD = r.FindControl("chkD") as CheckBox;
D = chkD.Checked;
}
}
}
Gridview:
<asp:GridView ID="gvRights" runat="server" Width="100%" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" AutoGenerateColumns="False" OnRowDataBound="gvRights_RowDataBound">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="Page ID" />
<asp:BoundField DataField="PageName" HeaderText="Page Name" />
<asp:BoundField DataField="PageDesc" HeaderText="Page Desc" />
<asp:TemplateField HeaderText="Create"></asp:TemplateField>
<asp:TemplateField HeaderText="Read"></asp:TemplateField>
<asp:TemplateField HeaderText="Update"></asp:TemplateField>
<asp:TemplateField HeaderText="Delete"></asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
If you are adding your checkboxes programmatically you need to add them back in on each page load in the pageinit (before page_load). This way the controls are added on each postback and will get their values filled from the viewstate.
An easier way is to actually add the Checkboxes in your template field in the definition
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkC" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox runat="server" ID="chkC" />
</EditItemTemplate>
</asp:TemplateField>

How to hide and show the DetailsView in the Master-Details GridView & DetailsView?

I am trying to follow and utilize the explained example in ASP.NET website that is about Quiz Engine. I have a Master-Details in the result page where when the user selects one of his answered quesitons in the GridView, the details of that question will be displayed in the DetailsView underneath the GridView. Everything works fine. What I want now is just making the DetailsView (which is the details of the answered question) hidden unless the user selects one of the answered questions. So how to do that?
I set visibility of the DetailsView to false, but I don't know how to hide/show based on the user click on the SELECT option.
My ASP.NET code:
<tr>
<td>
<asp:GridView ID="resultGrid" runat="server" DataKeyNames="QuestionID" SelectedIndex="0"
AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateSelectButton="True" OnSelectedIndexChanged="resultGrid_SelectedIndexChanged" Width="555px">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" CssClass="generaltext" HorizontalAlign="Center" />
<Columns>
<asp:BoundField DataField="QuestionID" HeaderText="Question" />
<%--<asp:BoundField DataField="CorrectAnswer" HeaderText="Correct Answer" />--%>
<asp:BoundField DataField="UserAnswer" HeaderText="Your Answer" />
<asp:BoundField DataField="Result" HeaderText="Result" />
</Columns>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" CssClass="boldtext" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [Question], [Answer1], [Answer2], [Answer3], [QuestionID], [QuestionOrder], [Answer4], [CorrectAnswer], [AnswerExplanation], [QuizID] FROM [Question] WHERE ([QuizID] = #QuizID) ORDER BY [QuestionOrder]">
<SelectParameters>
<asp:SessionParameter Name="QuizID" SessionField="QuizID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td>
<asp:DetailsView ID="answerDetails" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" Height="45px" Width="552px" DataSourceID="SqlDataSource1"
AutoGenerateRows="False" DataKeyNames="QuestionID" Visible="false">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" CssClass="generaltext" />
<FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" CssClass="boldtext" Width="100px" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Fields>
<asp:BoundField DataField="Question" HeaderText="Question"
SortExpression="Question" />
<asp:BoundField DataField="Answer1" HeaderText="A"
SortExpression="Answer1" />
<asp:BoundField DataField="Answer2" HeaderText="B"
SortExpression="Answer2" />
<asp:BoundField DataField="Answer3" HeaderText="C"
SortExpression="Answer3" />
<asp:BoundField DataField="Answer4" HeaderText="D"
SortExpression="Answer4" />
<asp:BoundField DataField="CorrectAnswer" HeaderText="Correct Answer"
SortExpression="CorrectAnswer" HeaderStyle-BackColor="lightgreen" />
<asp:BoundField DataField="AnswerExplanation" HeaderText="Explanation"
SortExpression="AnswerExplanation" HeaderStyle-BackColor="lightgreen" />
</Fields>
</asp:DetailsView>
</td>
</tr>
Code-Behind code:
public partial class Results : System.Web.UI.Page
{
Object bShowDetailsView;
protected void Page_Load(object sender, EventArgs e)
{
bShowDetailsView = false;
ArrayList al = (ArrayList)Session["AnswerList"];
if (al == null)
{
Response.Redirect("default.aspx");
}
resultGrid.DataSource = al;
resultGrid.DataBind();
// Save the results into the database.
if (IsPostBack == false)
{
// Calculate score
double questions = al.Count;
double correct = 0.0;
for (int i = 0; i < al.Count; i++)
{
Answer a = (Answer)al[i];
if (a.Result == Answer.ResultValue.Correct)
correct++;
}
double score = (correct / questions) * 100;
string username = HttpContext.Current.User.Identity.Name.ToString().Replace("ARAMCO\\", "");
SqlDataSource userQuizDataSource = new SqlDataSource();
userQuizDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["testConnectionString"].ToString();
userQuizDataSource.InsertCommand = "INSERT INTO [UserQuiz] ([QuizID], [DateTimeComplete], [Score], [Username]) VALUES (#QuizID, #DateTimeComplete, #Score, #Username)";
userQuizDataSource.InsertParameters.Add("QuizID", Session["QuizID"].ToString());
userQuizDataSource.InsertParameters.Add("DateTimeComplete", DateTime.Now.ToString());
// "N4" is for displaying four decimal places, regardless of what the value is
userQuizDataSource.InsertParameters.Add("Score", score.ToString("N4"));
userQuizDataSource.InsertParameters.Add("Username", username);
int rowsAffected = userQuizDataSource.Insert();
if (rowsAffected == 0)
{
// Let's just notify that the insertion didn't
// work, but let' s continue on ...
errorLabel.Text = "There was a problem saving your quiz results into our database. Therefore, the results from this quiz will not be displayed on the list on the main menu.";
}
}
}
protected void resultGrid_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataSource1.FilterExpression = "QuestionOrder=" + resultGrid.SelectedValue;
bShowDetailsView = true;
answerDetails.Visible = bShowDetailsView;
}
}
why not make the first record in resultGrid selected by default because the event you are handling is SelectedIndexChanged but not Selected/Unselected (i dont know whether these are there or not)

Paging in gridview

My gridView:
<asp:GridView ID="gridView1" runat="server" CellPadding="4" AllowPaging="true" PageSize="5" emptydatatext="No data available."
CssClass="datagrid"
ForeColor="#333333" GridLines="None"
onrowcreated="gridView1_RowCreated"
onpageindexchanging="gridView1_PageIndexChanging">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
And my codebehind:
protected void gridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView1.PageIndex = e.NewPageIndex;
BindDataGrid();
}
protected void BindDataGrid()
{
DataSet ds = new DataSet();
ds = dbM.GetInfo(name, mobilePhone, info1); //get info to BD and save in "ds"
gridView1.DataSource = ds;
gridView1.DataBind();
}
and the "Paging" does not work. It shows the first 5 rows, but does not show the number of paging
What´s wrong???
Please help
thanks
Try adding some pager settings in the GridView tag:
<PagerSettings Mode="NextPreviousFirstLast" Position="TopAndBottom" />
If that works, you can change it to your desired appearance. There are many choices, including
FirstPageImageUrl
FirstPageText
LastPageImageUrl
LastPageText
Mode (such as Numeric or
NumericFirstLast)
NextPageImageUrl
NextPageText
PageButtonCount
Position
PreviousPageImageUrl
PreviousPageText
Visible`
Add the PagerSettings-Property to the GridView-Markup and set it to True:
PagerSettings-Visible="true"
Edit: but it should be true by default, so i'm not sure if this will change anything
Use **"PageIndexChanged"**
protected void gridView1_PageIndexChanged(object sender, GridViewPageEventArgs e)
{
try
{
gridView1.PageIndex = e.NewPageIndex;
BindDataGrid();
;
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

Categories