ASPxGridView and LinqServerModeDataSource, inserting rows by stored procedure - devexpress

I have a page using ASPxGridView and to fill the GridView I use a LinqServerModeDataSource control who fetches it data through a SQL View from a MS SQL Server. So far so good but here comes the problem.
I want to insert data in the database so I'm building a custom form
<Templates>
<EditForm>
Company Name: <dx:ASPxTextBox ID="CompanyName" runat="server" />
Company Mail: <dx:ASPxTextBox ID="Email" runat="server" />
<dx:ASPxGridViewTemplateReplacement ID="UpdateButton" ReplacementType="EditFormUpdateButton" runat="server" />
<dx:ASPxGridViewTemplateReplacement ID="CancelButton" ReplacementType="EditFormCancelButton" runat="server" />
</EditForm>
</Templates>
Here is an example of the custom form
Pretty basic stuff, in this scenario the Company name goes to one table and the email to another. This is all handled by calling a Stored Procedure. Or thats the plan.
Does anyone know how to do this?
It feels like I've been trying it all, LinqServerModeDataSource1_Inserting, ASPxGridView1_RowInserting and so on but nooo. Here is one of the failing codes. And the devexpress documentation is even worse, but lets not go there its not a happy place.
protected void LinqServerModeDataSource1_Inserting(object sender, DevExpress.Data.Linq.LinqServerModeDataSourceEditEventArgs e)
{
// Some magic to insert data here
ASPxGridView1.CancelEdit();
}
So, any advice or help is highly appreciated.
Thanks!

"I want to insert data in the database so I'm building a custom form" ASPxGridView can do all that for you without you having to make a custom template at least with sqldb
If i would define a delete command and or edit command below to the sqldatasource i could already delete and edit the information in the gridview
<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False"
ClientIDMode="AutoID" DataSourceID="SqlDataSource1">
<Columns>
<dx:GridViewCommandColumn VisibleIndex="0">
<EditButton Visible="True">
</EditButton>
<NewButton Visible="True">
</NewButton>
<DeleteButton Visible="True">
</DeleteButton>
</dx:GridViewCommandColumn>
<dx:GridViewDataTextColumn FieldName="Naam" VisibleIndex="0">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="Adres" VisibleIndex="1">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="Postcode" VisibleIndex="2">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="Plaats" VisibleIndex="3">
</dx:GridViewDataTextColumn>
</Columns>
</dx:ASPxGridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Name], [Address], [Postcode], [City] FROM [Somewhere]">
</asp:SqlDataSource>
But you can if you really want to use a custom made insert or delete
protected void ASPxGridView4_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
{
DataColumn[] esl = new DataColumn[] { dt.Columns["SQLWaarde"] };
if (ds.Tables[0].PrimaryKey == null || ds.Tables[0].PrimaryKey == esl)
{
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["SQLWaarde"] };
}
DataRow[] delRow = ds2.Tables[0].Select("IndWaardeType = '" + e.Values[1] + "' AND SQLWaarde = '" + e.Values[2] + "'");
ds2.Tables[0].Rows.Remove(delRow[0] as DataRow);
e.Cancel = true;
ASPxGridView4.CancelEdit();
Session["ds2"] = ds2;
}
protected void ASPxGridView4_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
{
ndr2 = ds2.Tables[0].NewRow();
ndr2[0] = e.NewValues[0];
ndr2[1] = e.NewValues[1];
ndr2[2] = e.NewValues[2];
ds2.Tables[0].Rows.Add(ndr2);
e.Cancel = true;
ASPxGridView4.CancelEdit();
Session["ds2"] = ds2;
}
That's how i did it last time. I made use of datatables and stored that in sessions bla bla realy just trying out but it works alright.

Related

Unable to get selected item of dx:ASPxListBox on ASPxGridView_Updating event of devexpress control

I have used dx:ASPxGridView where I have one dx:GridViewDataTextColumn with EditItemTemplate which contain dx:ASPxListBox. When I click on update command I am not able to get selected items of dx:ASPxListBox under ASPxGridView_Updating.
<dx:ASPxGridView
ID="ASPxGridView"
runat="server"
AutoGenerateColumns="False"
DataSourceID="TradersDS"
KeyFieldName="TraderId">
<SettingsEditing Mode="PopupEditForm" PopupEditFormWidth="600px" />
<ClientSideEvents RowDblClick="function(s, e)
{
s.StartEditRow(e.visibleIndex);
}"
EndCallback="PrepareGridViewForNewDesing" Init="PrepareGridViewForNewDesing" />
<Columns>
....
<dx:GridViewDataTextColumn FieldName="CounterParty" VisibleIndex="3">
<EditItemTemplate>
<dx:ASPxListBox ID="lstCounterParty" runat="server" SelectionMode="CheckColumn" EnableSelectAll="true"
Width="285"
Height="300"
DataSourceID="CounterPartiesDS"
ValueField="ID"
ValueType="System.String"
TextField="Name">
<%-- <ClientSideEvents SelectedIndexChanged="function(s, e) {lbModels.PerformCallback('1');}" />--%>
</dx:ASPxListBox>
</EditItemTemplate>
</dx:GridViewDataTextColumn>
...
</Columns>
</dx:ASPxGridView>
C# Code..
protected override void ASPxGridView_Updating(object sender, ASPxDataUpdatingEventArgs e)
{
var gridView = sender as ASPxGridView;
GridViewDataColumn list = gridView.Columns["CounterParty"] as GridViewDataColumn;
var counterPartyListBox = (ASPxListBox)gridView.FindEditRowCellTemplateControl(list, "lstCounterParty");
string selectedItemsAsString = string.Empty;
foreach (ListEditItem item in counterPartyListBox.SelectedItems)
selectedItemsAsString += item.Value + ";";
base.ASPxGridView_Updating(sender, e);
}
Here I always get count 0 of SelectedItems. On addition to this My devExpress control version are 9.3.3
What is wrong with this code any help , guidance really appreciated.
Make sure that you set the ASPxListBox.ValueType property to the corresponding .NET type that matches the type of the "ValueField" column.
May be, according to the (ValueField="ID"), the (ASPxListBox.ValueType) should be numeric? (System.Int32, etc.)

Telerik Radgrid Says There are 0 Records, but the Query Returns 185 Records?

I have an ASP.NET WebForms Application and am encountering one of the oddest problems in my nine months of coding in ASP.NET.
I added two new pages that both use Telerik Radgrids. Both Radgrids are identical, so I will focus on one of them in the hopes that solving one of the problems will solve the other.
Html
<telerik:RadGrid ID="_radgrid" runat="server" Width="100%" Visible="true"
AutoGenerateColumns="false" OnSortCommand="_btnSearch_Click" PagerStyle-AlwaysVisible="true"
Skin="Office2007" AllowFilteringByColumn="true" AllowSorting="true" AllowPaging="true"
PageSize="50" OnNeedDataSource="_radgrid_NeedDataSource" OnItemDataBound="_radgrid_OnItemDataBound"
AllowMultiRowSelection="true">
<MasterTableView AllowFilteringByColumn="true" CommandItemDisplay="TopAndBottom">
<CommandItemTemplate>
<asp:Button ID="_btnResolve" runat="server" Text="Resolve" OnClick="_btnResolve_Click"
Visible="False" ClientIDMode="Inherit" />
</CommandItemTemplate>
<NoRecordsTemplate>
No records to display.</NoRecordsTemplate>
<Columns>
<telerik:GridBoundColumn DataField="Id" Visible="false" />
<telerik:GridBoundColumn DataField="Resolved" Visible="false" />
<telerik:GridClientSelectColumn UniqueName="CheckboxSelectColumn" FooterText="CheckBoxSelect footer"
Visible="false" />
<telerik:GridHyperLinkColumn DataNavigateUrlFields="Id" AllowFiltering="false"
DataNavigateUrlFormatString="~/UpdatePage.aspx?Id={0}"
Text="Update" UniqueName="UpdateHyperLink" />
<telerik:GridBoundColumn DataField="TradingPartnerName" HeaderText="Trading Partner Name" />
<telerik:GridBoundColumn DataField="DocumentType" HeaderText="Transaction Set" />
<telerik:GridBoundColumn DataField="DocumentID" HeaderText="Document ID" />
<telerik:GridBoundColumn DataField="Description" HeaderText="Description" />
</Columns>
</MasterTableView>
<ClientSettings>
<Selecting AllowRowSelect="true" />
<ClientEvents OnRowDblClick="RowDblClick" />
</ClientSettings>
</telerik:RadGrid>
Code Behind
protected void _radgrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
Fill_radgrid();
}
private void Fill_radgrid(bool dataBind = false)
{
//Data Manager is a class that I built that makes all of the Database calls. It returns a DataSet
_grdNegativeAck.DataSource = DataManager.GetRecords(_txtBoxId.Text, txtBoxDocumentType.Text, _chkBoxIncludeResolved.Checked, int.Parse(_ddlTradingPartner.SelectedValue));
if (dataBind)
_grdNegativeAck.DataBind();
}
protected void _radgrid_OnItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item is GridCommandItem)
{
//If the current user is authorized to resolve, show the Resolve button on the grid
if (currentUser.IsAuthorized))
{
GridCommandItem cmditem = (GridCommandItem)e.Item;
Button _btnResolve = (Button)cmditem.FindControl("_btnResolve");
_btnResolve.Visible = true;
_grdNegativeAck.MasterTableView.GetColumn("CheckboxSelectColumn").Visible = true;
}
}
else if (e.Item is GridDataItem)
{
//If the record is already resolved, do not show the checkbox on the side and color the record green
GridDataItem GDItem = e.Item as GridDataItem;
if (GDItem["Resolved"].Text.ToUpper() == "TRUE")
{
((e.Item as GridDataItem)["CheckboxSelectColumn"].Controls[0] as CheckBox).Visible = false;
(e.Item as GridDataItem).BackColor = System.Drawing.Color.Green;
}
}
}
Here's where things get interesting. On my localhost, when using the same database, I get 0 records returned. I checked the DataSet that I'm binding to, and there is literally 0 rows. When I query the database, I get 185 records no problem. I double-checked the parameters I pass to the query, and they're the same. When I put this same code on the Test site, the page will get 184 records... when it should be matching exactly and get 185 records.
The other page doesn't get any records on either my localhost or my test site.
I'm really at my wit's end here. Anyone encounter a similar situation or have somewhere they can point me?
_grdNegativeAck.DataSource = DataManager.GetRecords(_txtBoxId.Text, txtBoxDocumentType.Text _chkBoxIncludeResolved.Checked, int.Parse(_ddlTradingPartner.SelectedValue));
In the above line, you are missing a comma(,) after txtBoxDocumentType.Text.
Hope this will resolve your problem.

DevExpress TreeList settingSelection recursive

ASPX
<dx:ASPxTreeList ID="ASPxTreeListLocations" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSourceUserMetersTree" KeyFieldName="sno" ParentFieldName="ParentId"
Width="300px" SettingsSelection-Recursive="true" Theme="Office2010Black">
<Columns>
<dx:TreeListTextColumn FieldName="Text" VisibleIndex="0" Caption="Lokasyon">
</dx:TreeListTextColumn>
</Columns>
<SettingsBehavior AutoExpandAllNodes="True" />
<SettingsSelection Enabled="True" />
</dx:ASPxTreeList>
<asp:SqlDataSource ID="SqlDataSourceUserMetersTree" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>">
</asp:SqlDataSource>
CODEBEHID
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSourceUserMetersTree.SelectCommand = "SELECT * FROM Tree";
ASPxTreeListLocations.DataBind();
}
QUESTION:
Codes are working well. I want to recursive selection, but this property is not working. If I define SqlDataSource selectCommand in aspx side, it works. I cant find any solution. No error message. Any advice?
Thanks...
Try to add the option recursive = "true" to your tree settings,
NP

Grid view row updating and deleting

I have a grid view with below markup and below datasourse (linq query-stored procedure), I have added delete and update command field, but I do not know what code I have to add until deleting and updating for this grid view works.
<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:HyperLinkField DataNavigateUrlFields="Docid,Transid"
DataNavigateUrlFormatString="~/DocResult.aspx?Docid={0}&TransID={1}"
DataTextField="DocumentNo" HeaderText="Doc" />
<asp:BoundField DataField="title" HeaderText="Title" SortExpression="title" />
<asp:BoundField DataField="transmittal" HeaderText="transmittal" SortExpression="transmittal" />
<asp:BoundField DataField="Docid" HeaderText="Docid" Visible="false" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
protected void btnSearch_Click(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
var query = _DataContext.spQuickSearch(txtSearchKeywords.Text);
GridViewDocuments.Visible = false;
GridViewDocuments_Search.Visible = true;
GridViewDocuments_Search.DataSource = query;
GridViewDocuments_Search.DataBind();
}
The stored procedure spQuickSearch is like below:
ALTER proc [dbo].[spQuickSearch]
#Searchtext varchar(50)=null
AS
select DocId,TransId,DocumentNo,Title,TRANSMITTAL
from DocumentSum2
where DocumentNo like '%'+#SearchText + '%'
or Title like '%'+#SearchText + '%'
or TRANSMITTAL like '%'+#SearchText + '%'
You can handle commands like this:
protected void GridViewDocuments_Search_RowCommand(object sender, GridViewCommandEventArgs e)
{
string cmdArg = e.CommandArgument.ToString();
switch (e.CommandName)
{
case "Details":
//TODO: handle your Details command...
break;
case "Delete":
//TODO: handle your Delete command...
break;
}
}
You can add as many commands as you want (CommandName property for control). For example you can add another button and set Delete CommandName like this:
<asp:Button ID ="btn_Delete" Text="Delete" runat= "server" CommandName= "Delete" CommandArgument='<%#
Container.DataItemIndex%>' />
After command is completed you can call DataBind to refresh grid:
GridViewDocuments_Search.DataBind();
check this example
http://www.vkinfotek.com/gridview/gridview-commandfield.html
for detail
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.commandfield.showeditbutton.aspx

gridview with multi select listbox

HiI have a list box that is bound to a table in a database. it produces a list of companies. The user will then come along and select multiple companies that they want to view information about, and then they hit a selet button which ill display the company information (e.g company name, company site, address e.t.c) in a gridview underneath. however the issue that i am having is that it only displays ONE of the multiple companies selected and its always the top one.
Can someone please shed some light on how i get all the companies to be displayed in the gridview?
i am programming in vb.net
please see source code below
<asp:ListBox ID="ListBox1" runat="server"
DataSourceID="SqlDataSource11" DataTextField="compName"
DataValueField="compDataID" SelectionMode="Multiple" AutoPostBack="True"></asp:ListBox>
<asp:SqlDataSource ID="SqlDataSource11" runat="server"
ConnectionString="<%$ ConnectionStrings:IWSRiskAssessmentConnectionString %>"
SelectCommand="SELECT [compDataID], [compName] FROM [tblCompany] WHERE ([compDataID] <> #compDataID) ORDER BY [compName]">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="compDataID"
PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView
ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="compName" HeaderText="compName"
SortExpression="compName" />
<asp:BoundField DataField="Site Name" HeaderText="Site Name"
SortExpression="Site Name" />
<asp:BoundField DataField="Reference Number" HeaderText="Reference Number"
SortExpression="Reference Number" />
<asp:BoundField DataField="Asset" HeaderText="Asset" ReadOnly="True"
SortExpression="Asset" />
<asp:BoundField DataField="Location" HeaderText="Location"
SortExpression="Location" />
<asp:BoundField DataField="Block" HeaderText="Block" SortExpression="Block" />
<asp:BoundField DataField="Room" HeaderText="Room" SortExpression="Room" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:IWSRiskAssessmentConnectionString %>"
SelectCommand="SELECT tblCompany.compName, tblSite.siteName AS [Site Name], tblSite.siteUPRN AS [Reference Number], tblIncMain.incAsset + ' ' + CAST(tblIncMain.incNumber AS varchar) AS Asset, tblIncMain.incLocation AS Location, tblIncMain.incBlock AS Block, tblIncMain.incRoom AS Room FROM tblIncMain INNER JOIN tblSite ON tblIncMain.incSite = tblSite.siteID INNER JOIN tblCompany ON tblSite.siteCompany = tblCompany.compDataID WHERE (tblIncMain.incActive = 1) AND (tblSite.siteActive = 1) AND (tblIncMain.incRemoved = 0) AND (tblCompany.compDataID = #compDataID) ORDER BY [Site Name], tblIncMain.incAsset, tblIncMain.incNumber">
<SelectParameters>
<asp:ControlParameter ControlID="ListBox1" Name="compDataID"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
this is the source code :-) please take a look and any help is greatly appreciated
May be DataBind code executes on every request or you are not collecting selected items from the listbox.
Sub page_load()
if Not IsPostBack Then
End If
End sub
and to iterate Listbox items,
For Each item in ListBox1.Items
if item.Selected then
End If
Next
Your data source is only selecting 1 record. The ListBox will return the first value when you use a multiple select ListBox as a ControlParameter.
(tblCompany.compDataID = #compDataID)
What you want to do is have something with an IN statement such as
(tblCompany.compDataID in #compData)
You may need to do something in the code behind.
<asp:ListBox ID="ListBox1" runat="server"
AutoPostBack="True"
DataTextField="compName"
DataSourceID="SqlDataSource11"
DataValueField="compDataID"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
SelectionMode="Multiple">
</asp:ListBox>
Code behind
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = string.Empty;
foreach (ListItem li in ListBox1.Items)
{
if (li.Selected == true)
s += li.Value + ",";
}
if (s != string.Empty)
{
s = s.Substring(0, s.Length - 2); // chop off trailing ,
SqlDataSource2.SelectParameters["compData"].DefaultValue = s;
}
}
NOTE this hasn't been tested but it is one option you can try. Basically you want a IN not a = for your select to get all results.
ok so i added 'in' to my sql statement, however it still only picked up one selection from the list box instead of multiple this is the sql statement:
SELECT tblCompany.compName, tblSite.siteName AS [Site Name], tblSite.siteUPRN AS [Reference Number], tblIncMain.incAsset + " " + CAST(tblIncMain.incNumber AS varchar) AS Asset, tblIncMain.incLocation AS Location, tblIncMain.incBlock AS Block, tblIncMain.incRoom AS Room FROM tblIncMain INNER JOIN tblSite ON tblIncMain.incSite = tblSite.siteID INNER JOIN tblCompany ON tblSite.siteCompany = tblCompany.compDataID WHERE (tblIncMain.incActive = 1) AND (tblSite.siteActive = 1) AND (tblIncMain.incRemoved = 0) AND tblCompany.compDataID in(#compDataID) ORDER BY [Site Name], tblIncMain.incAsset, tblIncMain.incNumber

Resources