I have created a data access layer in my web app which uses ObjectDataSource instead of SqlDataSource. I have a FormView to update some data in my database. In my old asp.net code I had something like:
<asp:SqlDataSource ID="sdsTradeDetails" runat="server"
ConnectionString="<%$ ConnectionStrings:ForexDB %>"
SelectCommand="usp_GetTrade" SelectCommandType="StoredProcedure"
UpdateCommand="usp_UpdateTrade" UpdateCommandType="StoredProcedure"
<SelectParameters>
<asp:ControlParameter Name="tradeId" ControlID="grdTrades" PropertyName="SelectedDataKey.Value" />
</SelectParameters>
<UpdateParameters>
<asp:ControlParameter Name="tradeId" ControlId="frmTrade" PropertyName="SelectedValue" />
</UpdateParameters>
</asp:SqlDataSource>
Which worked fine. I have replaced the SqlDataSource with this:
<asp:ObjectDataSource
id="srcTrade"
TypeName="DatabaseComponent.DBUtil"
SelectMethod="GetTrade"
UpdateMethod="UpdateTrade"
runat="server">
<SelectParameters>
<asp:QueryStringParameter Name="tradeId" QueryStringField="tradeId" />
</SelectParameters>
<UpdateParameters>
<asp:ControlParameter Name="tradeId" ControlId="frmTrade" PropertyName="SelectedValue" />
</UpdateParameters>
</asp:ObjectDataSource>
But now I get this error when I click the Update button in my FormView:
Exception Details:
System.InvalidOperationException:
ObjectDataSource 'srcTrade' could not
find a non-generic method
'UpdateTrade' that has parameters:
symbol, pctAccountRisked,
tradeSetupId, lotsPerUnit,
initialStopPrice, tfCode, MAEPips,
MFEPips, tradeGrade, executionGrade,
tradeTypeId, comment, tradeId.
In my DBUtil class I have this for UpdateTrade:
public void UpdateTrade(
int tradeId,
string symbol,
decimal pctAccountRisked,
string tradeSetupId,
decimal lotsPerUnit,
decimal initialStopPrice,
string tfCode,
int MAEPips,
int MFEPips,
int tradeGrade,
int executionGrade,
string comment)
{
SqlCommand cmd = new SqlCommand("usp_UpdateTrade");
cmd.Parameters.AddWithValue("#tradeId", tradeId);
cmd.Parameters.AddWithValue("#symbol", symbol);
cmd.Parameters.AddWithValue("#pctAccountRisked", pctAccountRisked);
cmd.Parameters.AddWithValue("#tradeSetupId", tradeSetupId);
cmd.Parameters.AddWithValue("#lotsPerUnit", lotsPerUnit);
cmd.Parameters.AddWithValue("#initialStopPrice", initialStopPrice);
cmd.Parameters.AddWithValue("#tfCode", tfCode);
cmd.Parameters.AddWithValue("#MAEPips", MAEPips);
cmd.Parameters.AddWithValue("#MFEPips", MFEPips);
cmd.Parameters.AddWithValue("#tradeGrade", tradeGrade);
cmd.Parameters.AddWithValue("#executionGrade", executionGrade);
cmd.Parameters.AddWithValue("#comment", comment);
UpdateTable(cmd, "trade");
}
and this for GetTrade:
public DataTable GetTrade(int tradeId)
{
SqlCommand cmd = new SqlCommand("usp_GetTrade");
cmd.Parameters.AddWithValue("#tradeId", tradeId);
return FillDataTable(cmd, "trade");
}
Please help!
Hi your UpdateTrade method and the passing parameters from your datasource are missmatching. please recheck them
Related
Greetings i have this Gridview, ASP.NET has a Wizard to bind Data to Gridview, it gives you the TSQL query in an asp.net tag, but i was wondering how to do it in C# in code-behind.
HTML:
<asp:SqlDataSource ID="SqlDataSourceMain" runat="server"
ConnectionString="<%$ ConnectionStrings:Laptop %>" SelectCommand="SELECT [fCodeProducts],
[fCodeGroup], [fName], [fPrice], [fImageName],
[fDesc], [fMojoodi], [Namayesh],
[FileAddress] FROM tProducts WHERE (fCodeGroup = 12)
OR (fCodeGroup = #fCodeGroup) AND (Namayesh = 'True')
ORDER BY fCodeGroup">
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" DefaultValue="200" Name="fCodeGroup" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
If you need to change the SqlDataSource on code behind, you can do it like this:
SqlDataSourceMain.SelectCommand = "Select * from tProducts where Id=#MyParameter";
SqlDataSourceMain.SelectParameters["MyParameter"].DefaultValue = 1;
SqlDataSourceMain.DataBind();
You use it the exact same way, just bind it and bind it to your control.
Here is an Example that goes into more depth.
I'm learning ASP and I get stuck to update the database using asp SqlDataSource and GridView.
I have the following controls:
<asp:SqlDataSource ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:BPersonalConnectionString %>"
OldValuesParameterFormatString="original_{0}"
ConflictDetection="CompareAllValues"
SelectCommand="SELECT [Marca], [Nume], [Prenume], [Salariu], [Profesia] FROM [Salariati]"
UpdateCommand="update [Salariati] set [Marca] = Marca, [Nume] = Nume, [Prenume] = Prenume, [Salariu] = Salariu, [Profesia] = Profesia
where [Marca] = #original_Marca">
<UpdateParameters>
<asp:Parameter Name="Marca" Type="Int16"/>
<asp:Parameter Name="Nume" Type="String" Size="20"/>
<asp:Parameter Name="Prenume" Type="String" Size="20" />
<asp:Parameter Name="Salariu" Type="Int32" />
<asp:Parameter Name="Profesia" Type="String" Size="10" />
<asp:Parameter Name="original_Marca" Type="Int16" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView"
runat="server"
DataSourceID="SqlDataSource1"
AutoGenerateColumns="true"
AutoGenerateEditButton="true"
DataKeyNames="Marca"
AllowPaging="true"
PageSize="3"></asp:GridView>
Whenever I try to edit and update a item I dont get any result. The grid shows me exact same values as before the update. I did not wrote any code in code behind file.
I looked to some other examples already done on this subject but I was unable to identify the cause of the update problem.
Any hints?
Thanks!!!
Use the code Behind to fill gridView, it's much easier and offer you more handling and customization to gridView binding
here you will find some guide for the simplest way to connect gridView with sql data source.
If you want to do this by creating a method that returns a DataSet as well as passing parameters to execute the query then do something like this I will post the same thing returning a DataTable as well but it's pretty straight forward it works with any query that you pass dynamically
public static DataSet ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
return ds;
}
}
if you want to return a DataTable
public static DataTable ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
return ds.Tables[0];
}
}
You added parameters, but where is the value?
And look to your query: to some parameters you didn't used #, but for last one used. Change your query to the following:
UpdateCommand="update [Salariati] set [Marca] = #Marca, [Nume] = #Nume, [Prenume] = #Prenume, [Salariu] = #Salariu, [Profesia] = #Profesia
where [Marca] = #original_Marca">
And then your parameters:
<asp:ControlParameter ControlID="YourControlID" Name="Marca" PropertyName="Text" />
<asp:ControlParameter ControlID="YourControlID" Name="Nume" PropertyName="Text" />
<asp:ControlParameter ControlID="YourControlID" Name="Prenume" PropertyName="Text" />
<asp:ControlParameter ControlID="YourControlID" Name="Salariu" PropertyName="Text" />
<asp:ControlParameter ControlID="YourControlID" Name="Profesia" PropertyName="Text" />
<asp:ControlParameter ControlID="YourControlID" Name="original_Marca" PropertyName="Text" />
My query looks like this:
<asp:SqlDataSource ID="UpdateFullNameSQL" runat="server" ConnectionString="<%$ ConnectionStrings:UserQueries %>" ProviderName="<%$ ConnectionStrings:UserQueries.ProviderName %>"
UpdateCommand="update users set firstname = :changefirstname, lastname = :changelastname where username = :currentusername">
<UpdateParameters>
<asp:ControlParameter ControlID="ChangeFirstNameBox" Name="changefirstname" PropertyName="Text" Type="Empty" />
<asp:ControlParameter ControlID="ChangeLastNameBox" Name="changelastname" PropertyName="Text" Type="Empty" />
</UpdateParameters>
<SelectParameters>
<asp:ControlParameter ControlID="UsernameBox" Name="currentusername" PropertyName="Text" Type="Empty" />
</SelectParameters>
</asp:SqlDataSource>
So I have two parameters that I want to update from and one parameter that I want to use to change the data where it matches withthe selectparameter's data. And when I want to execute it, it shows an ORA-01008 exception.
My code-behind only has a updatefullnamesql.update(); function.
What am I missing here/doing wrong?
In update command you should use # instead of :. I.E.:
UpdateCommand="update users set firstname = #changefirstname,
lastname = #changelastname where username = #currentusername;"
Additionally you have to specify the #currentusername as update parameter
<UpdateParameters>
...
<asp:ControlParameter ControlID="UsernameBox"
Name="currentusername" PropertyName="Text" Type="Empty" />
</UpdateParameters>
I have a listview
<asp:ListView ID="ListViewNews" runat="server" DataSourceID="SqlDataSourceAddNews" DataKeyNames="Id" InsertItemPosition="LastItem" OnItemCommand="ListViewNews_ItemCommand">
<InsertItemTemplate>
<asp:FileUpload ID="FileUpload2" runat="server" />
</InsertItemTemplate>
and the sqldatasource:
<asp:SqlDataSource runat="server" ID="SqlDataSourceAddNews"
ConnectionString='<%$ ConnectionStrings:ConnectionStringSchool %>'
DeleteCommand="DELETE FROM [News] WHERE [Id] = #Id"
InsertCommand="INSERT INTO News(TITLE, SUMMARY, TEXT, DATETIME, PHOTO, [FILE])
VALUES (#TITLE, #SUMMARY, #TEXT, #DATETIME, #PHOTO, #FILE)"
SelectCommand="SELECT * FROM [News] ORDER BY DATETIME DESC">
<DeleteParameters>
<asp:Parameter Name="Id" Type="Int32"></asp:Parameter>
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="TITLE" Type="String"></asp:Parameter>
<asp:Parameter Name="SUMMARY" Type="String"></asp:Parameter>
<asp:Parameter Name="TEXT" Type="String"></asp:Parameter>
<asp:Parameter Name="DATETIME" Type="DateTime"></asp:Parameter>
<asp:Parameter Name="PHOTO" Type="String"></asp:Parameter>
<asp:Parameter Name="FILE" Type="String"></asp:Parameter>
</InsertParameters>
</asp:SqlDataSource>
I want to get the id of insert command to name the uploaded photo
protected void ListViewNews_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
string strID= ....get id here....;
FileUpload fu2 = (FileUpload)ListViewNews.InsertItem.FindControl("FileUpload2");
if (fu2.HasFile)
{
string aut = strID + ".jpg";
fu2.SaveAs(Server.MapPath("~/images/NewsPhotos/" + aut));
}
}
}
Any idea for a simple solution how to get the id here?
Try this,
Change your insert command to:
InsertCommand="INSERT INTO News(TITLE, SUMMARY, TEXT, DATETIME, PHOTO, [FILE])
VALUES (#TITLE, #SUMMARY, #TEXT, #DATETIME, #PHOTO, #FILE);
SELECT #Id = SCOPE_IDENTITY();"
Add New Output Parameter to InsertParameters List
<asp:Paramter Direction="Output" Name="Id" Type="Int32" />
Move your file saving code to SQLDataSource Inserted method, you cannot access this generated id in ItemCommand Event directly
protected void SqlDataSourceAddNews_Inserted(object sender, EventArgs e)
{
string strId = e.Command>parameters("#Id").Value.ToString();
FileUpload fu2 = (FileUpload)ListViewNews.InsertItem.FindControl("FileUpload2");
if (fu2.HasFile)
{
string aut = strID + ".jpg";
fu2.SaveAs(Server.MapPath("~/images/NewsPhotos/" + aut));
}
}
I'm using an UpdatePanel in ASP.Net WebForms to upload a image. I set the Image.ImageUrl to the full virtual path to the image (/images/news/filenname.jpg), but I only want to save the filename in the database (filename.jpg). How do I customize the SqlDataSource to only take part of the URL?
<asp:SqlDataSource
ID="SqlDataSourceNews"
runat="server"
ConnectionString="<%$ ConnectionStrings:connectionString %>"
UpdateCommand="UPDATE [foo] SET [pic] = #pic WHERE [id] = #id">
<UpdateParameters>
<asp:Parameter Name="pic" Type="String" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="pic" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
You can set the update parameters on page_load and use substring function to get only file name from full url:
protected void Buton_Click(object sender, EventArgs e)
{
SqlDataSource1.UpdateParameters["pic"].DefaultValue = "string fetched from substring method";
SqlDataSource1.Update();
}