I am trying to nest a grid within a grid.
To populate the most inner grid i need the KeyValue from both the Grids' direct parent, and the parent of the Grids' parent.
How can i retrieve the MasterRowKeyValue from the outter most parent?
I have 3 grids nested like so:
<dxwgv:ASPxGridView ID="gridParents" runat="server" ObjectDataSource="odsParents" KeyFieldName="ParentId">
<SettingsDetail ShowDetailRow="true" />
<Columns>
<dx:GridViewDataColumn FieldName="ParentIdId" Visible="false" />
<dx:GridViewDataColumn FieldName="Title" />
</Columns>
<Templates>
<DetailRow>
<dxwgv:ASPxGridView ID="gridParentsChilren" runat="server" ObjectDataSource="odsParentsChildren" KeyFieldName="ChildId" OnBeforePerformDataSelect="gridParentsChilren_DataSelect">
<SettingsDetail ShowDetailRow="true" IsDetailGrid="true" />
<Columns>
<dx:GridViewDataColumn FieldName="ChildId" Visible="false" />
<dx:GridViewDataColumn FieldName="Title" />
</Columns>
<Templates>
<dxwgv:ASPxGridView ID="gridParentsChilrenRoles" runat="server" ObjectDataSource="odsParentsChildrenRoles" KeyFieldName="RoleId" OnBeforePerformDataSelect="gridParentsChilrenRoles_DataSelect">
<SettingsDetail ShowDetailRow="true" IsDetailGrid="true" />
<Columns>
<dx:GridViewDataColumn FieldName="RoleId" Visible="false" />
<dx:GridViewDataColumn FieldName="Title" />
</Columns>
</dxwgv:ASPxGridView>
</Templates>
</dxwgv:ASPxGridView>
</DetailRow>
</Templates>
</dxwgv:ASPxGridView>
<asp:ObjectDataSource id="odsParents" runat="server" SelectMethod="GetParents" />
<asp:ObjectDataSource id="odsParentsChildren" runat="server" SelectMethod="GetParentsChildren">
<SelectParameters>
<asp:Parameter Name="parentid" Type="Object" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:ObjectDataSource id="odsParentsChildrenRoles" runat="server" SelectMethod="GetParentsRoles">
<SelectParameters>
<asp:Parameter Name="childid" Type="Object" />
<asp:Parameter Name="parentid" Type="Object" />
</SelectParameters>
</asp:ObjectDataSource>
When the OnBeforePerformDataSelect is called for the first Detail grid, i set the select parameters DefaultValue like this:
odsParentsChildren.SelectParameters["parentid"].DefaultValue = ((ASPxGridView)sender).GetMasterRowKeyValue().ToString();
For the most inner (the second) nested grid, i need to set one of my parameters to the MasterRowKeyValue of the most outter grid.
Something like:
odsParentsChildrenRoles.SelectParameters["childid"].DefaultValue = ((ASPxGridView)sender).GetMasterRowKeyValue().ToString();
odsParentsChildrenRoles.SelectParameters["parentid"].DefaultValue = ((ASPxGridView)sender).Master.GetMasterRowKeyValue().ToString();
How do I achieve this?
This can be done if you determine the master ASPxGridView instance for the processed detail. This can be done using the following code:
protected void ASPxGridView1_BeforePerformDataSelect(object sender, EventArgs e) {
ASPxGridView subDetail = sender as ASPxGridView;
GridViewDetailRowTemplateContainer container = subDetail.NamingContainer as GridViewDetailRowTemplateContainer;
ASPxGridView detail = container.Grid;
odsParentsChildrenRoles.SelectParameters["parentid"].DefaultValue = detail.GetMasterRowKeyValue();
}
Another possible version
protected void gvMyGridView_BeforePerformDataSelect(object sender, EventArgs e)
{
var gvMyGridView = sender as ASPxGridView;
var parentRow = gvMyGridView.NamingContainer as GridViewDetailRowTemplateContainer;
odsChildDataSource.SelectParameters["Id"].DefaultValue = parentRow .KeyValue.ToString();
}
Related
I have 2 JQGrids on my ASPX page. When an Invoice is selected on the top grid, it loads the corresponding data on the second.
My issue is with exporting. When I export the page using SelectPDF, the 2nd Grid View is always empty.
Here is what it looks like on the page:
...and this is what the exported PDF looks like, there is no data in the second grid.
Here is the ASPX code:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" Inherits="Invoicing" Codebehind="Invoicing.aspx.cs" EnableEventValidation="false" %>
<%# Register Assembly="Trirand.Web" TagPrefix="trirand" Namespace="Trirand.Web.UI.WebControls" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<link href="themes/CustomStyles.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/jquery-ui.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/trirand/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/trirand/jquery.jqGrid.min.js" type="text/javascript"></script>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Indigo2.Properties.Settings.Constr %>"
SelectCommand="SELECT [invoice_number],[invoice_date],[custid],[inv_splitter] FROM [Indigo].[dbo].[invoices]" CancelSelectOnNullParameter="false"
UpdateCommand=""
DeleteCommand="">
<UpdateParameters>
<asp:Parameter Name="invoice_number" Type="Int32" />
<asp:Parameter Name="invoice_date" Type="DateTime" />
<asp:Parameter Name="custid" Type="String" />
<asp:Parameter Name="inv_splitter" Type="String" />
</UpdateParameters>
<DeleteParameters>
</DeleteParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:Indigo2.Properties.Settings.Constr %>"
SelectCommand="SELECT [inv_item_id],[description],[unit_sell],[qty],[inv_section],[inv_orderby],[inv_splitter],[ref_date_start],[ref_date_end],[custid],[cust_po],[invoice_number], unit_sell * qty as Price FROM [Indigo].[dbo].[invoice_items] WHERE (invoice_number = #invoice_number) " CancelSelectOnNullParameter="false"
UpdateCommand="UPDATE Invoice_items SET cust_po=#cust_po, description=#description, ref_date_start=CONVERT(datetime, #ref_date_start, 105), ref_date_end=CONVERT(datetime, #ref_date_end, 105), unit_sell=#unit_sell, qty=#qty WHERE inv_item_id=#inv_item_id"
DeleteCommand="DELETE FROM Invoice_items WHERE inv_item_id=#inv_item_id">
<SelectParameters>
<asp:Parameter DefaultValue="" Name="invoice_number" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="inv_item_id" Type="Int32" />
<asp:Parameter Name="cust_po" Type="String" />
<asp:Parameter Name="description" Type="String" />
<asp:Parameter Name="ref_date_start" Type="DateTime" />
<asp:Parameter Name="ref_date_end" Type="DateTime" />
<asp:Parameter Name="unit_sell" Type="Decimal" />
<asp:Parameter Name="qty" Type="Int32" />
</UpdateParameters>
<DeleteParameters>
<asp:Parameter Name="inv_item_id" Type="Int32" />
<asp:Parameter Name="cust_po" Type="String" />
</DeleteParameters>
</asp:SqlDataSource>
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<br />
<trirand:JQGrid runat="server" ID="JQGrid1" DataSourceID="SqlDataSource1" Width="1200"
OnRowSelecting="JQGrid1_RowSelecting">
<Columns>
<trirand:JQGridColumn DataField="invoice_number" HeaderText="ID" PrimaryKey="True" Width="100" />
<trirand:JQGridColumn DataField="invoice_date" Editable="true" DataFormatString="{0:d}" Width="100"/>
<trirand:JQGridColumn DataField="custid" Editable="true" Width="100"/>
</Columns>
<ToolBarSettings ShowEditButton="true" ShowRefreshButton="True" ShowAddButton="true" ShowDeleteButton="true" ShowSearchButton="True" />
</trirand:JQGrid>
<br />
<trirand:JQGrid runat="server" ID="JQGrid2" DataSourceID="SqlDataSource2" Width="1200" Height="100%" maxHeight="300" hidegrid="true" ondatarequested="JQGrid2_DataRequested">
<Columns>
<trirand:JQGridColumn CSSClass="indent" DataField="description" Editable="true" Width="800"/>
<trirand:JQGridColumn DataField="inv_section" Editable="true" />
<trirand:JQGridColumn DataField="ref_date_start" Editable="true" DataFormatString="{0:d}" Width="200"/>
<trirand:JQGridColumn DataField="ref_date_end" Editable="true" DataFormatString="{0:d}" Width="200"/>
<trirand:JQGridColumn DataField="cust_po" Editable="true" />
<trirand:JQGridColumn DataField="unit_sell" Editable="true" DataFormatString="{0:c}" Width="200"/>
<trirand:JQGridColumn DataField="qty" Editable="true" Width="200"/>
<trirand:JQGridColumn DataField="price" Editable="false" DataFormatString="{0:c}" Width="200" >
</trirand:JQGridColumn>
</Columns>
<PagerSettings PageSize="12" />
<GroupSettings CollapseGroups="false">
<GroupFields>
<trirand:GroupField
DataField="inv_section"
HeaderText="<b>{0}</b>"
GroupSortDirection="Asc"
ShowGroupColumn="false"
ShowGroupSummary="true"/>
<trirand:GroupField
DataField="cust_po"
HeaderText="PO Reference: <b>{0}</b>"
GroupSortDirection="Asc"
ShowGroupColumn="false"
ShowGroupSummary="false"/>
</GroupFields>
</GroupSettings>
<AppearanceSettings ShowFooter="true" />
<ToolBarSettings ShowEditButton="true" ShowRefreshButton="True" ShowAddButton="true" ShowDeleteButton="true" ShowSearchButton="True" />
</trirand:JQGrid>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button runat="server" ID="ExportToPDFButton" Text="Export to PDF" OnClick="BtnCreatePdf_Click" />
...and here is the underlying code
using System;
using System.Web.UI;
using Trirand.Web.UI.WebControls;
using System.IO;
using System.Data;
using SelectPdf;
using System.Web;
public partial class Invoicing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JQGrid2.Visible = true; //was false!!!!!!!!!!!!!!
if (Session["invoice_number"] != null)
{
JQGrid2.Visible = true;
SqlDataSource2.SelectParameters["invoice_number"].DefaultValue = Session["invoice_number"] as string;
}
}
protected void JQGrid2_DataRequested(object sender, Trirand.Web.UI.WebControls.JQGridDataRequestedEventArgs e)
{
DataTable dt = e.DataTable; // get only the current page data
double poTotal = 0;
foreach (DataRow row in dt.Rows)
{
double poValue = (double)row["price"];
poTotal += poValue;
}
string formattedMoneyValue = String.Format("{0:C}", poTotal);
JQGrid2.Columns.FromDataField("price").FooterValue = formattedMoneyValue.ToString();
JQGrid2.Columns.FromDataField("qty").FooterValue = "Total:";
}
protected void JQGrid1_RowSelecting(object sender, Trirand.Web.UI.WebControls.JQGridRowSelectEventArgs e)
{
Session["invoice_number"] = JQGrid1.SelectedRow;
JQGrid2.Visible = true;
SqlDataSource2.SelectParameters["invoice_number"].DefaultValue = Session["invoice_number"] as string;
}
//Start of Select PDF Code//
private bool startConversion = false;
protected void BtnCreatePdf_Click(object sender, EventArgs e)
{
startConversion = true;
}
protected override void Render(HtmlTextWriter writer)
{
if (startConversion)
{
Session["invoice_number"] = JQGrid1.SelectedRow;
JQGrid2.Visible = true;
SqlDataSource2.SelectParameters["invoice_number"].DefaultValue = Session["invoice_number"] as string;
// get html of the page
TextWriter myWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(myWriter);
base.Render(htmlWriter);
// instantiate a html to pdf converter object
HtmlToPdf converter = new HtmlToPdf();
// create a new pdf document converting the html string of the page
PdfDocument doc = converter.ConvertHtmlString(
myWriter.ToString(), Request.Url.AbsoluteUri);
// save pdf document
doc.Save(Response, false, "Sample.pdf");
// close pdf document
doc.Close();
}
else
{
// render web page in browser
base.Render(writer);
}
}
}
Please can someone help me, with what I need to do so that the data from the second grid is passed to the PDF when exported.
UPDATE:
If I hardcode the default value for the datasource on the second grid it exports the correct info.
<SelectParameters>
<asp:Parameter DefaultValue="1000" Name="invoice_number" Type="Int32" />
</SelectParameters>
For some reason when I export, it seems to be clearing this parameter value, if I set it dynamically.
The SelectPdf convert loads your web page using a new Session, so it does not know your dynamically set parameters. You need to send them in the url, if possible.
I want to modify items in gridview by update command but in same page i have also a textbox with required validation.
i'm unable to update in gridview when require validation occur in textbox Control
And Source Code here...
<div class="row">
<asp:Button ID="Button1" runat="server" CssClass="btn btn-primary" Text="Add" OnClick="Button1_Click"
ValidationGroup="btn" />
<asp:Button ID="Button2" runat="server" CssClass="btn btn-primary" Text="Reset" OnClick="Button2_Click"
CausesValidation="False" />
<asp:Button ID="Button3" runat="server" CssClass="btn btn-primary" Text="Show" CausesValidation="False"
OnClick="Button3_Click" />
</div>
</form> </div> </div>
<asp:GridView ID="GridView1" runat="server" CssClass="table-hover table-responsive table-condensed table-bordered"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="id"
DataSourceID="SqlDataSource1" Visible="False">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
SortExpression="id" />
<asp:BoundField DataField="Loc" HeaderText="Location" SortExpression="Loc" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:mycon %>"
SelectCommand="SELECT * FROM [location]" DeleteCommand="Delete From Location Where Id=#id"
UpdateCommand="update location set loc=#loc where id=#id">
<DeleteParameters>
<asp:ControlParameter ControlID="TextBox1" Name="id" PropertyName="Text" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="loc" />
<asp:ControlParameter ControlID="GridView1" Name="id" PropertyName="SelectedValue" />
</UpdateParameters>
</asp:SqlDataSource>
and cs code here
protected void Button1_Click(object sender, EventArgs e)
{
string qry = "insert into location (loc)values(#loc) ";
SqlConnection con = Connection.Getconnection();
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#loc", TextBox1.Text);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation!", "<script>alert('Successfully Add')</script>");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation!", "<script>alert('Error')</script>");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox1.Text = string.Empty;
}
protected void Button3_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
}
Please try to add try catch for button1_click to catch Exceptions.
Validation group has an effect only when the value of the CausesValidation property is set to true.and validation group need to specify a value
Please Refer this Link
I have used a gridview and linqdatasourse , the gridview will be fill by a linq-stored procedure after clicking a search button.
I did it like below but my grid view is empty.
It seems LinqDataSource2_Selecting does not work.
Please help what is the problem?
public void LinqDataSource2_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
_DataContext = new EDMSDataContext();
var subjectFilter = e.WhereParameters["Subject"];
var query = _DataContext.spQuickSearchDoc(subjectFilter);
e.Result = query;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
this.LinqDataSource2.WhereParameters["Subject"].DefaultValue = this.txtSearchKeywords.Text;
GridViewDocuments.Visible = false;
GridViewDocuments_Search.Visible = true;
this.GridViewDocuments_Search.DataBind();
}
Stored procedure:
ALTER PROCEDURE [dbo].[spQuickSearchDoc]
#Searchtext varchar(50)=null
AS
select DocId,DocumentNo,Title,Unit
from tblDocuments
where DocumentNo like '%'+#SearchText + '%'
or Title like '%'+#SearchText + '%'
or Unit like '%'+#SearchText + '%'
Gridview:
<asp:GridView ID="GridViewDocuments_Search" runat="server" AutoGenerateColumns=False Visible="False" onrowcommand="GridViewDocuments_Search_RowCommand"
DataKeyNames="DocID" PageSize="100" >
<Columns>
<asp:TemplateField HeaderText = "Details">
<ItemTemplate>
<asp:Button ID ="btn_Show" Text="Details" runat= "server" CommandName= "Details" CommandArgument='<%#
Container.DataItemIndex%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DocumentNo" HeaderText="DocumentNo" SortExpression="DocumentNo" />
<asp:BoundField DataField="title" HeaderText="Title" SortExpression="title" />
<asp:BoundField DataField="Docid" HeaderText="Docid" Visible="false" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource2" runat="server"
ContextTypeName="EDMSDataContext" OnSelecting="LinqDataSource2_Selecting">
<WhereParameters>
<asp:ControlParameter Name="Subject"
ControlID="txtSearchKeywords"
PropertyName="Text"
Type="String" />
</WhereParameters>
</asp:LinqDataSource>
You need to add DataSourceID to the GridView, as in:
<asp:GridView ID="GridViewDocuments_Search" runat="server"
. . DataSourceID="LinqDataSource2">
Since it's not set, the GridView is being bound to NULL.
I'm pretty lost at this point (been working at it for a while not and am hitting a wall / deadline) but the error message I am being thrown is after I hit btnupdate to update the fields in the database.
Full Error Message:
Could not find control 'txtTitle' in ControlParameter 'Title'.
Page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div class="floater">
<h3>Books</h3>
<asp:DropDownList
id="DropDownList_Books"
DataSourceId="srcBooks"
DataTextField="Title"
DataValueField="Id"
Runat="server" />
<asp:Button ID="btnSelect" runat="server" Text="View Detials" Width="106px"
onclick="btnSelect_Click" />
</div>
<asp:GridView
id="grdBooks"
DataSourceID="srcBooks_Description"
Runat="server" Visible="False" />
<asp:Button ID="btnEdit" runat="server" onclick="btnEdit_Click" Text="Edit" />
</div>
<asp:Button ID="btnCancel" runat="server" onclick="btnCancel_Click"
Text="Cancel" Visible="False" />
<asp:FormView
id="frmEditBook"
DataKeyNames="Cat_Id"
DataSourceId="srcBooks_Description"
DefaultMode="Edit"
Runat="server" Visible="False"
style="z-index: 1; left: 391px; top: 87px; position: absolute; height: 111px; width: 206px" >
<EditItemTemplate>
<asp:Label
id="lblTitle"
Text="Title:"
AssociatedControlID="txtTitle"
Runat="server" />
<asp:TextBox
id="txtTitle"
Text='<%#Bind("Title")%>'
Runat="server" />
<br />
<asp:Label
id="lblDescription"
Text="Description:"
AssociatedControlID="txtDescription"
Runat="server" />
<asp:TextBox
id="txtDescription"
Text='<%#Bind("Description")%>'
Runat="server" />
<br />
<asp:Button
id="btnUpdate"
Text="Update"
CommandName="Update"
Runat="server" />
</EditItemTemplate>
</asp:FormView>
<asp:SqlDataSource ID="srcBooks" runat="server"
ConnectionString="Data Source=****;;Initial Catalog=***;Persist Security Info=True;User ID=****;Password=****"
onselecting="srcBooks_Selecting" ProviderName="System.Data.SqlClient" SelectCommand="SELECT Title,Id FROM PARTIN_ID">
</asp:SqlDataSource>
<asp:SqlDataSource ID="srcBooks_Description" runat="server"
ConnectionString="Data Source=****, 14330";Initial Catalog=****;Persist Security Info=True;User ID=****;Password=****"
onselecting="srcBooks_Selecting" ProviderName="System.Data.SqlClient" SelectCommand="SELECT * FROM PARTIN_INFO WHERE Cat_ID=#Id" UpdateCommand="UPDATE PARTIN_INFO SET Title=#Title,
Description=#Description WHERE Cat_Id=#Id">
<SelectParameters>
<asp:ControlParameter
Name="Id"
Type="int32"
ControlID="DropDownList_Books"
PropertyName="SelectedValue" />
</SelectParameters>
<UpdateParameters>
<asp:ControlParameter Name="Title" ControlId="txtTitle" PropertyName="Text"/>
<asp:ControlParameter Name="Description" ControlId="txtDescription" PropertyName="Text"/>
<asp:ControlParameter Name="Id" ControlId="DropDownList_Books" PropertyName="SelectedValue"/>
</UpdateParameters>
</asp:SqlDataSource>
</form>
</body>
</html>
Code Behind:
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void srcBooks_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void btnSelect_Click(object sender, EventArgs e)
{
grdBooks.Visible = true;
}
protected void btnCancel_Click(object sender, EventArgs e)
{
frmEditBook.Visible = false;
}
protected void btnEdit_Click(object sender, EventArgs e)
{
frmEditBook.Visible = true;
btnCancel.Visible = true;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
try
{
srcBooks_Description.Update();
}
catch (Exception except)
{
// Handle the Exception.
}
}
}
}
You -can- refer to the control adequately.
You need to prefix the controlid value of your update parameters with the control id of your enclosing view (FormView 'frmEditBook' in this case)
Replace the UpdateParamters section of your SqlDataSource with the following:
<UpdateParameters>
<asp:ControlParameter Name="Title" ControlId="frmEditBook$txtTitle" PropertyName="Text"/>
<asp:ControlParameter Name="Description" ControlId="frmEditBook$txtDescription" PropertyName="Text"/>
<asp:ControlParameter Name="Id" ControlId="DropDownList_Books" PropertyName="SelectedValue"/>
</UpdateParameters>
Note that
ControlId="DropDownList_Books"
remains the same as this control is not within the bounds of the FormView.
I don't recommend using the 'full name' provided by the browser... particularly if you're using master pages... it could change as you rearrange your layouts.
As you can see, the problem is the context. You can also put your sqldatasource inside the formview where the control being refered to is (not properly and very limited but could work)
Let's say you have a detailsview with two dropdowns in it, and one is dependant from another. What works for me is to put the Datasource in the same context (parent control) as the control refered and this will eliminate the need to reference the full path of the control.
My two cents is that this is very reminiscent on how you must reference controls in Access Forms with subforms. :)
<asp:DetailsView runat="server">
<asp:TemplateField>
<EditTemplate>
<asp:DropDownList id="ParentDDL" Datasource="SQLDataSource1">
</asp:DropDownList>
</EditTemplate>
</asp:TemplateField>
<asp:TemplateField>
<EditTemplate>
<asp:DropDownList id="ParentDDL" Datasource="SQLDatasource2">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * from table where field1=#field">
<SelectParameters>
<asp:ControlParameter ControlID="ParentDDL" Name="field"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</EditTemplate>
</asp:TemplateField>
</asp:DetailsView>
You need to refer to your control with its full name.
You can easily find the control's full name when you open the page in the browser. Simply view source and you will see it.
The problem is that txtTitle is inside a FormView so it's not accesible in the way you're trying to do on the SqlDataSource. You can't access it direclty by ID.
Here you have an MSDN article that may help to to work with a FormView and SqlDataSource
you shouldn't have used <asp:ControlParameter.. but <asp:Parameter.. and the SqlDataSource control with the help of the bind method is intelligent enough to locate the controls to get values from for the parameters.
Update this portion of the sqlDataSource this way:
....
<UpdateParameters>
<asp:Parameter Name="Title" Type="String"/>
<asp:Parameter Name="Description" Type="String"/>
<asp:Parameter Name="Id" Type="Int32"/>
</UpdateParameters>
.....
Please note the Type attribute and supply the relevant type.
(The problem is SqlDataSource control cannot explicitly access controls defined in a databound control)
Sorry for the convoluted title, but that is the best way I could think to phrase it.
Basically, I have a column of data that is a URL (lets call it URL-A), and another that is hidden which is also a URL(URL-B). I have a function called ConvertURL(string URLin) in the codebehind that will take URL-A and turn it into URL-B.
So in this gridview, if someone were to edit an entry using the native gridview/datasource functionality and change URL-A, how do I get it to run this new URL-A through ConvertURL() and update the URL-B field?
Here is a simple representation of the code (not the actual code):
Code-behind function:
public string ConvertURL(string URLin)
{
Int32 iLocation = URLin.IndexOf("WWW.XYZ.COM");
if (iLocation >= 0)
{
string checkurl = URLin.Replace("WWW.XYZ.COM", "STAGING.XYZ.COM");
return checkurl;
}
else
{
return URLin;
}
}
Data-Source:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:My_AppConnectionString %>"
SelectCommand="SELECT [URL_A], [URL_B], [URLName] FROM [My_App] WHERE ([IsActive] = #IsActive)"
OldValuesParameterFormatString="original_{0}"
UpdateCommand="UPDATE [My_App] SET [URL_A] = #URL_A, [URL_B] = #URL_B, [URLName] = #URLName, [IsActive] = #IsActive WHERE [ID] = #original_ID">
<SelectParameters>
<asp:Parameter DefaultValue="True" Name="IsActive" Type="Boolean" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="URL_A" Type="String" />
<asp:Parameter Name="URL_B" Type="String" />
<asp:Parameter Name="URLName" Type="String" />
<asp:Parameter Name="IsActive" Type="boolean" />
<asp:Parameter Name="original_ID" Type="Int32" />
<asp:Parameter Name="original_URL_A" Type="String" />
<asp:Parameter Name="original_URL_B" Type="String" />
<asp:Parameter Name="original_URLName" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
And Lastly the GridView:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
onrowediting="GridView1_RowEditing"
AutoGenerateColumns="False" CellPadding="3" DataKeyNames="ID"
DataSourceID="SqlDataSource1" EnableModelValidation="False" ForeColor="Black"
GridLines="Vertical" AllowSorting="True" BackColor="White"
BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
AutoGenerateEditButton="True" CausesValidation="false">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" Visible="False" />
<asp:BoundField DataField="URL_A" HeaderText="URL A"
SortExpression="URL_A" />
<asp:BoundField DataField="URL_B" HeaderText="URL B"
SortExpression="URL_B" **Visible="False"** />
<asp:BoundField DataField="URLName" HeaderText="URL Name"
SortExpression="URLName" />
<asp:CheckBoxField DataField="IsActive" HeaderText="Active"
SortExpression="IsActive" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
</asp:GridView>
So to summarize: A user will see a gridview with 3 fields to edit, one of which is URL_A (URL_B is hidden). When they hit edit and update the URL_A field I want to run URL_A through the ConvertURL() function and use that output as the data for URL_B when the update is performed.
I appreciate the help in advance!
Use the RowUpdating event of the grid view and change the new value for URL_B. In that event you will have access to the old values of the row as well as the new values. You can change the new values before they are sent to the data source for the actual update.
Add the event handler to the grid view in the ASPX:
<asp:GridView ID="GridView1" runat="server"
...
OnRowUpdating="GridView1_RowUpdating">
And in the code file handle the event:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Find the current value for URL_A
string urlA = (string)e.NewValues["URL_A"];
// Get the corresponding value for URL_B from the method
string urlB = ConvertURL(urlA);
// Set the new value for the URL_B column before it's sent to the SqlDataSource
e.NewValues["URL_B"] = urlB;
}