How to get gridview clickable cell data value to new page aspx - sql

I have two columns in a GridView where every cell of 1 column is hyperlinked.
<asp:GridView ID="gvBlogList" runat="server" DataKeyNames="Id"
AutoGenerateColumns="False" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLinkField DataTextField="id"
HeaderText="Blog id" NavigateUrl="detailspage.aspx" />
</ItemTemplate>
<ItemStyle Width="150px"></ItemStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
How can I get cell value in 2nd page as a session variable?
Thanks!

As per the what I understand from your question, you want to catch the value of the cell that is clicked, store it in session and make it accessible on the page that have redirect to. This is possible and you can try a flow like this :
You can use the GridView's inbuilt method onRowCommand in this case to generate a server side event and you can then identify which cell was clicked and lastly, you can get its value by index. The below code is a demonstration that you can try and manipulate as per your requirement. This is a sample where a Linkbutton is used in Gridview and on the click of it, its value is fetched.
You can also try to use the CommandName and CommandArgument properties if you want to assign that particular control a value that you may use at the server side.
protected void Grd1_RowCommand(object sender, GridViewCommandEventArgs e)
{
LinkButton lnk = (LinkButton)e.CommandSource;
string value = lnk.Text;
}
And for storing it in Session, you just have to make use of Session["yourVarName"] = value;. And this value can be accessed on the other page.
Hope this helps.

Related

How to Add an Empty, Unbound, Comment Column to a GridView?

I've put together a GridView table in ASP.net that allows users to approve a series of records. As part of this approval process, I'd like to provide an empty column for the user to provide comments where necessary. The only records showing up will be records that haven't been approved yet, thus, no comments will need to be loaded. Once they are approved, users will not be able to view these records again.
How do I go about adding this empty column to my GridView? Again, there's no data to load into this column. Once approved, the records in the SQL Server table will be updated with a timestamp and comments.
Most of what I was able to find on here so far has been related to adding empty rows, but not columns. I'm completely new to ASP.net, so any help would be greatly appreciated.
Current Column Code:
asp:TemplateField HeaderText="Comment" ItemStyle-Width="500px" ItemStyle-Wrap="true" SortExpression="Comment" /
Just a simple solution I've quickly put together. It uses the OnRowCommand event of the GridView.
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="TextBox">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Text='<%# Eval("textfield") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UpdateButton">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Update" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//cast the sender back to a gridview
GridView gv = sender as GridView;
//cast the commandsource back to a button
Button btn = e.CommandSource as Button;
//cast the namingcontainer of the button back to a gridviewrow
GridViewRow row = btn.NamingContainer as GridViewRow;
//find the correct textbox using findcontrol and the index obtained from the row
TextBox tb = gv.Rows[row.DataItemIndex].FindControl("TextBox1") as TextBox;
//show result
Label1.Text = tb.Text;
}
UPDATE
Or if you want to update all the records at once by pressing a button.
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
TextBox tb = row.FindControl("TextBox1") as TextBox;
Label1.Text += tb.Text + "<br>";
}
}

ASP.net VB Listbox

I've seen many questions around this one, but none hitting it directly.
I put a listbox on a page and populate it with three items from an Access database. I have a button on that page that will extract several values including the selected item from the listbox. Or I want to anyway.
I can see the item selected in windows (highlighted) when I click the button, but when I try to select it no item is available as selected in the listbox. The ListBox1.SelectedIndex is alway -1.
Here is the code from the page:
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem Text="List1" />
<asp:ListItem Text="List2" />
<asp:ListItem Text="List3" />
</asp:ListBox>
Is there a property missing?
Here is the code from the code behind page:
Public Function getDept() As String
Dim dept As String
If ListBox1.SelectedIndex > -1 Then
dept = ListBox1.SelectedItem.Text
Else
dept = "CMS"
End If
Return dept
End Function
Please help, I have until about noon to figure this out.
There may some reasons:
1- Check if your page's viewstate is true.
2- Call your method after Page_Load event.
Where do you call the function?
Consider that you should call it after Page_Load event. Also your viewstate

Updating in an editable gridview once it has been displayed after the updatepanel it is in has been made visible by the user

I have been searching forums and trying to solve this for a few days now but I'm stuck. Apologies if this is something so simple and obvious that I have missed. Although I have found posts similar to my issue, they are not quite the same.
Here is the outline of what my Web app partly does:
shows a simple asp:dropdownlist
When the user selects a value, the appropriate updatepanel is made visible (these update panels are visible = false in the Page_Load code behind), showing an editable gridview:
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs)
If DropDownList1.SelectedItem.Value <> "0" Then
If DropDownList1.SelectedValue = "Activate or Inactivate Users" Then
UpdatePanel1.Visible = True
End If
...
<asp:GridView ID="GridView3" runat="server" AllowSorting="True" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="iMemberId" HeaderText="iMemberId" InsertVisible="False" ReadOnly="True" SortExpression="iMemberId" />
<asp:BoundField DataField="sFname" HeaderText="sFname" SortExpression="sFname" />
<asp:BoundField DataField="sSname" HeaderText="sSname" SortExpression="sSname" />
<asp:BoundField DataField="dDateCreated" HeaderText="dDateCreated" SortExpression="dDateCreated" />
<asp:BoundField DataField="sEmailAddress" HeaderText="sEmailAddress" SortExpression="sEmailAddress" />
<asp:BoundField DataField="sMobileNo" HeaderText="sMobileNo" SortExpression="sMobileNo" />
<asp:CheckBoxField DataField="bActiveMember" HeaderText="bActiveMember" SortExpression="bActiveMember" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" Runat="server" ConnectionString="<%$ ConnectionStrings:PTCCHomeTestConnectionString %>" SelectCommand="SELECT * FROM [MemberTable] ORDER BY [sSname]"
UpdateCommand="UPDATE MemberTable SET sFname = #sFname, sSname = #sSname, sEmailAddress = #sEmailAddress, sMobileNo =, bActiveMember = WHERE (iMemberId = #iMemberId)">
<UpdateParameters>
<asp:Parameter Name="sFname" />
<asp:Parameter Name="sSname" />
<asp:Parameter Name="sEmailAddress" />
<asp:Parameter Name="iMemberId" />
</UpdateParameters>
</asp:SqlDataSource>
</ContentTemplate>
Each gridview's select and update queries have been tested and work fine. I have tested the gridviews in a page where they are all visible ( and it all works fine, but I would like to have the only the appropriate gridview visible depending on which one the user selects from the dropdown list.
The user should then be able to click Edit on a chosen row and update it. The gridview displays fine, properly populated, but when the user clicks on the Edit (to update) link in a row I get the error:
"Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page...
Stack Trace:
[ArgumentException: Invalid postback or callback argument. Event validation is enabled using in configuration or in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +144
System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +111
System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument) +32
System.Web.UI.WebControls.GridView.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +9643314
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929"`
I have tried the following (but still the same error):
I added a Render sub that registers all the values from the select and update for event validation:
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
'override (page) Render and loop over the GridView Rows
Dim row As GridViewRow
For Each row In GridView3.Rows
If (row.RowType = DataControlRowType.DataRow) Then
Page.ClientScript.RegisterForEventValidation(New System.Web.UI.PostBackOptions(Me.GridView3, "Select$" + row.RowIndex.ToString()))
Page.ClientScript.RegisterForEventValidation(New System.Web.UI.PostBackOptions(Me.GridView3, "Update$" + row.RowIndex.ToString()))
End If
Next
MyBase.Render(writer)
...
I also tried to rebind the gridview and datasource:
If Not (IsPostBack) Then
SqlDataSource2.DataBind()
GridView3.DataBind()
End If
I have also tried to add the EnableEventValidation="false" in the Page tag. What happens is that I now can press the Edit link but then the UpdatePanel disappears (as per the Page_Load) and when I then select the value from the dropdown list it appears again with the row in Edit mode, but with blanks instead of the row's current values.
I also tried defining the datasource of the gridview outside of the same updatePanel that the gridview is in but that did not make any difference.
Just to confirm, if I don't make the UpdatePanels visible=false in the Page_Load code so the user can see all of them then the gridviews work fine with updating rows. This makes me think that the issue lies with the statelessness as if I understand correctly, when an Edit link is pressed the Page_Load code is called again and the dropdownlistvalue is no longer held, thus making the updatepanel which the gridview is in visible=false again.
So, is there any other way to make the updatepanels hidden depending on the dropdownlist selection that is not Page_Load? Could this be where a solution lies?
Or another way to have the dropdownlist chosen value persist after an Edit link (Page_Load call) is done?
I think that I'm sort of on the right track but it would be really helpful to get a little guidance.

LinqDataSource "OnSelecting" event not firing on Post-backs

I have a web page with two dropdownlist controls, each bound to separate LinqDataSource objects. One displays a list of Categories and the other displays a list of Articles. The Category choice drives Article list (at least, that's my intended behaviour). The Article list is also filtered based on the users language preference, stored in the Session and applied in the ArticleLinqDataSource_Selecting event handler.
<asp:Label runat="server" Text="Category Code:" AssociatedControlID="CategoryDropDownList" />
<asp:DropDownList runat="server" ID="CategoryDropDownList" DataSourceID="CategoryLinqDataSource" DataValueField="CategoryID" DataTextField="CategoryCode" AutoPostBack="true" />
...
<asp:Label runat="server" Text="Article Code:" AssociatedControlID="ArticleCodeDropDown" />
<asp:DropDownList runat="server" ID="ArticleCodeDropDown" DataSourceID="ArticleLinqDataSource" DataValueField="ArticleID" DataTextField="ArticleCode" OnDataBound="ArticleCodeDropDown_DataBound" />
...
<asp:LinqDataSource runat="server" ID="CategoryLinqDataSource"
ContextTypeName="Article.Data.ArticleDataContext"
TableName="Categories" Select="new (CategoryID, CategoryCode)">
</asp:LinqDataSource>
...
<asp:LinqDataSource runat="server" ID="ArticleLinqDataSource"
ContextTypeName="Arcicle.Data.ArticleDataContext"
TableName="Articles" OrderBy="ArticleCode"
Select="new (ArticleID, ArticleCode)"
OnSelecting="ArticleLinqDataSource_Selecting">
</asp:LinqDataSource>
This all works fine when the page first loads. The Category list contains the all the available category values, and the first category in the list is selected. And the corresponding Articles for the first category are displayed appropriately in the Article dropdown control. However, when I change the category (a post-back happens because I have it set to AutoPostBack="true", the Article dropdown does not get refreshed. In other words, the OnSelecting event is not getting fired on subsequent postbacks. Is this the expected bahaviour? If it is, how do I get around this?
You need to call DataBind on the DropDownList in the CategoryDropDownList's SelectedIndexChanged event. It doesn't happen on its own.
e.g.
Protected Sub CategoryDropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CategoryDropDownList.SelectedIndexChanged
ArticleCodeDropDown.DataBind()
End Sub

ComboBox's Selected Value Changed On Lost Focus in VB.NET

I have a datagridview(dgv) with a DataGridViewComboBoxColumn(colLocation)
colLocation.AutoComplete = False
colLocation.HeaderText = "Stored to"
colLocation.DataSource = DB.getLocation()
colLocation.DisplayMember = "description"
colLocation.ValueMember = "id"
I added the colLocation to dgv.
"descirption" contains Unicode characters. I can see the comboBox correctly and choose the item.
The problem is when the comboBox lost the focus, the value is changed to first item of the comboBox.
Any suggestion?
Updated:
I found out that the ComboBox doesn't change the data when the DisplayMember is in English characters.
It changes only when the DisplayMember is in Unicode chracter. Any idea for how could solve this? – tunwn 0 secs ago
Your .aspx page should have something like so:
<asp:DropDownList Width="90px" ID="ddlExpenseTypes" OnSelectedIndexChanged="ddlExpenseTypes_SelectedIndexChanged" DataSource='<%# GetExpenseTypes() %>' SelectedValue='<%# Bind("ExpenseReasonID") %>' DataTextField="ExpenseReasonID" DataValueField="ExpenseReasonID" AutoPostBack="true" runat="server" ></asp:DropDownList>
That is you need a functional call for index changed. A function call for filling the drop down ist (DataSource) and a function call to set the SelectedValue of the drop down list.
Is this DataGridView databound? You haven't specified a value for DataPropertyName, so there's nothing for colLocation.ValueMember's ID selection to bind to.