I have a little detailsview where i can add some data to my DB.
The detailsview's code:
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
DataSourceID="orderSqlDataSource" DefaultMode="Insert" Height="50px"
Width="333px" DataKeyNames="ID" CellPadding="4" ForeColor="#333333"
GridLines="None" oniteminserted="DetailsView1_ItemInserted"
onprerender="DetailsView1_PreRender">
<CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
<EditRowStyle BackColor="#E9ECF1" />
<FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
<Fields>
<asp:BoundField DataField="userid" HeaderText="Azonosító"
SortExpression="userid" ReadOnly="True" />
<asp:BoundField DataField="quantity" HeaderText="Mennyiség (kg)"
SortExpression="quantity" />
<asp:TemplateField HeaderText="Mit rendel" SortExpression="Mit rendel">
<InsertItemTemplate>
<asp:DropDownList ID="ordertypeDropDownList" runat="server"
DataSourceID="ordertypeDDLSqlDataSource" DataTextField="name"
DataSource='<%# Bind("ordertype") %>'
SelectedValue='<%# Bind("ordertype") %>'
DataValueField="ID">
</asp:DropDownList>
<asp:SqlDataSource ID="ordertypeDDLSqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:dotnetConnectionString %>"
SelectCommand="SELECT [name], [ID] FROM [product]"></asp:SqlDataSource>
</InsertItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowInsertButton="True" CancelText="Mégsem"
InsertText="Elküld" />
</Fields>
<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" />
</asp:DetailsView>
Here is the code behind for the page_load event:
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
MembershipUser user = Membership.GetUser(User.Identity.Name);
string userID = user.ProviderUserKey.ToString();
((TextBox)DetailsView1.Rows[0].Cells[1].Controls[0]).Text = userID;
}
}
As you can see i fill the first boundfield from the page_load.
The problem is that the first boundfield (userid, or in my native language "azonosító") is important because of the database, but i don't want to let the user see his/her userid.
If i make the boundfield hidden (visible=false), it won't be reachable with the code in the page_load.
How can i bound the current userID to that field, when the field is hidden, or how can i get this work without boundfield for the ID?
Thanks in advance!
If the user doesn't need to know or interact with the value you are inserting, then it is quite easy to inject parameter values into the insert call that the DetailsView sends to your datasource control. Just use the DetailsView.Inserting event DetailsViewInsertEventArgs parameter as shown.
Code:
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
if (User.Identity.IsAuthenticated)
{
MembershipUser user = Membership.GetUser(User.Identity.Name);
string userID = user.ProviderUserKey.ToString();
e.Values.Add("userid", userID);
}
}
As you might expect, this method makes the BoundField completely unnecessary :)
Use Template Field and place a label and bind it with userid. You can access the label in your codebehind irrespective of it is invisible.
<asp:DetailsView runat="server" ID="dv" >
<Fields>
<asp:TemplateField Visible="false" >
<ItemTemplate>
<asp:Label ID="lb" runat="server" Text='<%# Bind("userid") %>' />
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
// In your code behind
string userid = ((Label)dv.Rows[0].FindControl("lb")).Text(); // give the correct index
Related
I am using Visual Studio 2015 and Entity Framework 6. I have a gridview displaying orders from a database. However, I need a user to be able to click a row and be taken to another page for editing that row after a dialog box confirmation.
This is what I have:
<asp:GridView ID="gridOrders" runat="server" Height="184px" Width="1359px" AutoGenerateColumns="false"
AllowSorting="true" >
<HeaderStyle Font-Bold="true" Font-Size="16pt" BackColor="#cc0000" ForeColor="Black" />
<RowStyle Font-Size="12pt" BackColor="#afadad" ForeColor="White"/>
<AlternatingRowStyle BackColor="#afadad" ForeColor="White" />
<Columns>
<asp:CommandField HeaderText="" SelectText="CANCEL ORDER" ShowSelectButton="true" ControlStyle-ForeColor="White" />
<asp:BoundField HeaderText="First Name" DataField="FirstName" SortExpression="FirstName" />
How do I make the row selection to another page happen with a dialog that asks user if they are sure?
Change your aspx page with the below code
<asp:GridView ID="gridOrders" runat="server" Height="184px" Width="1359px" AutoGenerateColumns="False"
AllowSorting="True">
<HeaderStyle Font-Bold="true" Font-Size="16pt" BackColor="#cc0000" ForeColor="Black" />
<RowStyle Font-Size="12pt" BackColor="#afadad" ForeColor="White" />
<AlternatingRowStyle BackColor="#afadad" ForeColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lnkCancelOrder" runat="server" OnClientClick="return confirm('Are you sure to redirect?')" OnClick="lnkCancelOrder_Click" CausesValidation="False" CommandArgument='<%#Eval("OrderID") %>' CommandName="Select" Text="CANCEL ORDER"></asp:LinkButton>
</ItemTemplate>
<ControlStyle ForeColor="White" />
</asp:TemplateField>
<asp:BoundField HeaderText="First Name" DataField="FirstName" SortExpression="FirstName" />
</Columns>
</asp:GridView>
Write the c# code as follows
You can redirect to another page and pass the orderID as QueryString, and retrieve the complete order information by orderID and show that in an edit mode form
protected void lnkCancelOrder_Click(object sender, EventArgs e)
{
LinkButton lnk = sender as LinkButton;
string orderID = lnk.CommandArgument;
Response.Redirect("AnotherPage.aspx?orderId="+orderID);
}
Write under the <asp:TemplateField> of Gridview as
<asp:LinkButton ID="anchrTag" runat="server" PostBackUrl="Your edit page url" OnClientClick="return confirm('Are u sure to leave this page and want to go for edit?');">Edit</asp:LinkButton>
I'm using a DetailView to insert data into a GridView via an sqlDataSource. I'm attempting to set one of the fields of the DetailView to the current date/time on Page Load so the user does not have to enter the date/time. I get no errors - however, the "Update Date" field of the DetailView fails to display the current date/time.
This is my hypertext:
<asp:DetailsView
id="dtlShipModes"
DataSourceID="SqlDataSource1"
AutoGenerateRows="False"
DefaultMode="Insert"
Runat="server" BackColor="White" BorderColor="White" BorderStyle="Ridge"
BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None">
<EditRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
<Fields>
<asp:BoundField
DataField="ShipMode"
HeaderText="Ship Mode:" />
<asp:CheckBoxField
DataField="Active"
HeaderText="Active:" />
<asp:TemplateField HeaderText="Update Date:">
<EditItemTemplate>
<asp:TextBox ID="txtUpdateDate" runat="server" Text='<%# Bind("UpdateDate") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="txtUpdateDate" runat="server" Text='<%# Bind("UpdateDate") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("UpdateDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField
DataField="UpdateBY"
HeaderText="Update BY:" />
<asp:CommandField ShowInsertButton="true" InsertText="Add" />
</Fields>
<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" />
</asp:DetailsView>
This is the code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim txtupdatedby As String = DirectCast(dtlShipModes.FindControl("txtUpdateDate"), TextBox).Text
txtupdatedby = DateTime.Now.ToString
End Sub
Could I get some help please as to what I'm doing wrong?
To expand a little on Mych's answer, you would want to handle the ItemCreated event of the DetailsView:
<asp:DetailsView
id="dtlShipModes"
DataSourceID="SqlDataSource1"
AutoGenerateRows="False"
DefaultMode="Insert"
ItemCreated="dtlShipModes_ItemCreated"
Runat="server" BackColor="White" BorderColor="White" BorderStyle="Ridge"
BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None">
And then write the event handler like this:
protected void dtlShipModes_ItemCreated(Object sender, EventArgs e)
{
Dim txtupdatedby As TextBox = DirectCast(dtlShipModes.FindControl("txtUpdateDate"), TextBox)
txtupdatedby.Text = DateTime.Now.ToString
}
Notice that I changed your implementation a little, to use a reference to the TextBox, rather than the string.
This is all necessary because the DetailsView is not loaded with data yet in the Page's Load event.
You need to set your date when the Items in the DataView are being bound to the datasource. You need to use the ItemCreated event....
See... http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsview.itemcreated(v=vs.110).aspx
i'm new to asp.net. i'm doing one project. in that i've used one gridview and fetch datas from database using sqldatasource.
gridview code is
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="Library" CellPadding="4" ForeColor="#333333"
GridLines="None" OnRowDataBound="GridView1_RowDataBound" >
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:BoundField DataField="Sl_No" HeaderText="Sl_No" SortExpression="Sl_No" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Author" HeaderText="Author"
SortExpression="Author" />
<asp:BoundField DataField="Publication" HeaderText="Publication"
SortExpression="Publication" />
<asp:BoundField DataField="Available" HeaderText="Status"
SortExpression="Available" />
<asp:TemplateField HeaderText="Availability">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Available") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RIUserTaken" HeaderText="RIUserTaken"
SortExpression="RIUserTaken" Visible="False" />
<asp:TemplateField HeaderText="Taken By" ShowHeader="False">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("RIUserTaken", "{0}") %>'></asp:Label>
<asp:Button ID="SendRequest" runat="server" Text="Button" Visible="False"
onclick="SendRequest_Click" CommandName="SendRequestCmd" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Taken Date" InsertVisible="False"
ShowHeader="False">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("TakenDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" /> </asp:GridView>
code is one of the column of the grid view. if i click on that button, i've to store that button contains rows all datas in string variable. like
string slno="";
slno=gridview1.cells[0].text; (i'm not sure it is correct or not)
plz anyone help me??
thanks in advance :)
From msdn, you should check this.
GridView.SelectedIndexChanged event
void CustomersGridView_SelectedIndexChanged(Object sender, EventArgs e)
{
// Get the currently selected row using the SelectedRow property.
GridViewRow row = CustomersGridView.SelectedRow;
// Display the company name from the selected row.
// In this example, the third column (index 2) contains
// the company name.
MessageLabel.Text = "You selected " + row.Cells[2].Text + ".";
}
void CustomersGridView_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{
// Get the currently selected row. Because the SelectedIndexChanging event
// occurs before the select operation in the GridView control, the
// SelectedRow property cannot be used. Instead, use the Rows collection
// and the NewSelectedIndex property of the e argument passed to this
// event handler.
GridViewRow row = CustomersGridView.Rows[e.NewSelectedIndex];
// You can cancel the select operation by using the Cancel
// property. For this example, if the user selects a customer with
// the ID "ANATR", the select operation is canceled and an error message
// is displayed.
if (row.Cells[1].Text == "ANATR")
{
e.Cancel = true;
MessageLabel.Text = "You cannot select " + row.Cells[2].Text + ".";
}
}
Do these things
Step 1. Wire up a RowCommand Evnt to your GridView
Step 2. Inside that event at code-behind, do this
if(e.CommandName.Equals("SendRequestCmd"))
{
var clickedRow = ((Button)e.CommandSource).NamingContainer as GridViewRow;
// now access the cells like this
var clickedSLNo = clickedRow.cells[0].Text;
}
Update:
e.CommandSource definition
A instance of the System.Object class that represents the source of the command.
IButtonControl.CommandArgument definition
A control that implements the IButtonControl interface must implement the CommandArgument property and the CommandName property to indicate the argument and command name that are propagated to the Command event.
I have a web page with checkbox list to choose multiple crystal reports to view. I want to open these reports in new tabs or windows.
I tried this :
This is the show report button:
<asp:Button ID="Button2" runat="server" Text="Show Report" OnClick="ButtonShowReport_Click"
CssClass="button" OnClientClick="aspnetForm.target ='_blank';"/>
And this is my gridview control:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
RowStyle-HorizontalAlign="Center" AutoGenerateColumns="False"
DataKeyNames="AccountID">
<RowStyle BackColor="#>
<Columns>
<asp:TemplateField HeaderText="Choose Client's Accounts">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label id="lblAccountId" runat ="server" text='<%# Eval("AccountID")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="AccountID" HeaderText="AccountID" Visible="false"/>
<asp:BoundField DataField="AccountName" HeaderText="Account Name" />
<asp:BoundField DataField="Name" HeaderText="Client Name" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
My c# code looks like:
protected void ButtonShowReport_Click(object sender, EventArgs e)
{
string accountID;
int Rows = GridView1.Rows.Count;
for (int i = 0; i < Rows; i++)
{
//CheckBoxField cb = ((CheckBoxField)gvASH.Rows[i].Cells[1]).;
CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
if (cb.Checked == true)
{
accountID = ((Label)GridView1.Rows[i].FindControl("lblAccountID")).Text;//GridView1.DataKeys[i].Value.ToString();//GridView1.Rows[i].Cells[1].Text;
//Button2.Enabled = true;
openReport(accountID);
}
}
}
protected void openReport(string accountID)
{
//some code for setting parameters of the crystal report
//and for creating report key
Response.Redirect(string.Format("~/Report.aspx?ReportKey={0}",
ReportKey.ToString()),false);
}
So if the user checked 2 reports and clicked on the ShowReport button, it'll do the loop but opens only one new tab with the last report chosen ...
Any Suggestions please ??
Add this to the control which triggers the redirect. I know this works for Buttons/LinkButtons, not sure if it will work on a checkbox though.
OnClientClick="aspnetForm.target ='_blank';"
One method you might consider:
Instead of doing the Redirect to each report inside the code behind - dynamically generate some JavaScript that has uses window.open for each report. The javascript would look similar to this:
<script type="text/javascript">
window.open("<report1URL>", "_blank");
window.open("<report2URL>", "_blank");
...
window.open("<reportNURL>", "_blank");
</script>
Then, instead of doing a Response.Redirect, you should be able to do a Respone.Write() to get the browser to execute the code.
string myJavaScript= <dynamicallyGenerateJavascript>;
Response.Write(myJavaScript);
I have a Default.aspx page in which I have bind a Grid. In the Grid is a button named Details.
I also have a Details.aspx which has a GridView. If I click the button that exist in Default.aspx, there appears an Details.aspx page which appears empty.
When click the Detail button of a specific row, there appears the details of that button clicked. I am not understanding on how to pass the ID to Details.aspx.
Can anybody guide me to this please?
Details.aspx
<asp:GridView ID="DetailsGridView" runat="server" BackColor="White" AutoGenerateColumns="false"
BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataKeyNames="ID"
ForeColor="Black" GridLines="Vertical">
<FooterStyle BackColor="#CCCC99" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
Default.aspx:
<Columns>
<asp:BoundField HeaderText="First Name" DataField="FirstName" />
<asp:BoundField HeaderText="Last Name" DataField = "LastName" />
<asp:BoundField HeaderText="HomePhoneNumber" DataField="HomePhoneNumber" />
<asp:TemplateField HeaderText="ViewDetails">
<ItemTemplate>
<asp:Button ID="Deatils" runat="server" Text="Details" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:Button ID="Modify" runat="server" Text="Modify" />
<asp:Button ID="Delete" runat="server" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</div>
JavaScript
<script type="text/javascript">
function viewProfile(index)
{
var GridID = document.getElementById("PersonGridView");
var row=GridID.rows[parseInt(index)+1];
window.open('Details.aspx?coaid'+row);
}
</script>
Code Behind of Default.aspx:
protected void PersonGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var DataKeys = PersonGridView.DataKeys[e.Row.RowIndex];
DataKeys.Value.ToString();
var ID = DataKeys["ID"].ToString();
Button btnDetails = (Button)e.Row.FindControl("Deatils");
Button btnModify = (Button)e.Row.FindControl("Modify");
Button btnDelete = (Button)e.Row.FindControl("Delete");
btnModify.CommandName = "Modify";
btnDelete.CommandName = "Delete";
btnDetails.CommandName = "Deatils";
btnDelete.CommandArgument = btnModify.CommandArgument = btnDetails.CommandArgument = string.Format("{0}", ID);
btnDetails.Attributes["onclick"] = string.Format("viewProfile({0}); return false;", e.Row.RowIndex);
}
}
EDIT: I've modified my example to not use a HyperLink and instead will build a LinkButton that can navigate to your Details.aspx page passing the ID value in the QueryString:
Default.aspx:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton CommandName="Details" CommandArgument='<%# Eval("ID") %>' Text="Details" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Default.aspx.cs:
protected void PersonGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Details")
{
Server.Transfer("Details.aspx?ID=" + e.CommandArgument.ToString());
}
}
On the Grid when you click the button
do the following
public protected sub Button_Click(EventArgs e)
{
if (grid.SelectedItem != null)
{
var selectedRow = grid.SelectedItem ;
// do what ever you want to Selected Row that may be binding it to another Form etc.
}
Do the same for OnSelectedEvent if you want to do it that way instead.
public protected sub OnSelectedEvent_Click(EventArgs e)
{
if (grid.SelectedItem != null)
{
var selectedRow = grid.SelectedItem ;
// do what ever you want to Selected Row that may be binding it to another Form etc.
}