Customize SqlDataSource to store part of string - c#

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();
}

Related

SQLDataStore with output parameters, getting ParameterName not contained in this SqlParameterCollection error

The ultimate goal of what I am trying to accomplish is this:
Button at the bottom of a material order form Inserts a new record in the material order table with the ProjectID and current date. After the record is inserted, redirect the page to the new order id so it can be modified.
If I take out the OnInserted method that is supposed to grab the SCOPE_IDENTITY() output of the insert, the record inserts fine, but with the call, I keep getting "SQLParameter with ParameterName 'NewOrderID' is not contained by this SqlParameterCollection"
ASPX Formview
<asp:FormView ID="FvFooter" runat="server" DataKeyNames="OrderID"
DataSourceID="FvMatOrdersSQL" ForeColor="#333333" OnItemCommand="FvFooter_OnItemCommand">
<ItemTemplate>
<br/>
<b>Notes</b>
<br/>
<asp:Label ID="TxtNotes" runat="server" BorderStyle="Solid" BorderWidth="1"
Text='<%# Eval("Notes").ToString().Replace(Environment.NewLine, "<br />") %>'/>
<br/>
<asp:LinkButton ID="LbEditNotes" runat="server" CssClass="NoPrint"
CausesValidation="False" CommandName="Edit" Text="Edit"/>
<br/>
<br/>
<asp:Button ID="DeleteButton" runat="server" CausesValidation="False"
CssClass="NoPrint" CommandName="DeleteOrder" Text="Delete"/>
<asp:Button ID="NewButton" runat="server" CausesValidation="True"
CssClass="NoPrint" CommandName="NewOrder" Text="New Order"/>
<asp:Button ID="EmailButton" runat="server" CausesValidation="True"
CssClass="NoPrint" CommandName="Email" Text="Email"/>
</ItemTemplate>
</asp:FormView>
SQL DataSource
<asp:SqlDataSource ID="FvMatOrdersSQL" runat="server" ConnectionString="<%$ ConnectionStrings:ProjectLogicTestConnectionString %>"
SelectCommand="SELECT mo.OrderID, mo.ProjectID, p.ProjectName, mo.OrderedByEmpID, emp.Name,
mo.OrderDate, mo.DateNeeded, mo.ReasonID, mor.Description, mo.Notes
FROM tblMatOrder AS mo
LEFT OUTER JOIN tblMatOrderReason AS mor ON mo.ReasonID = mor.ReasonID
INNER JOIN tblProject AS p ON mo.ProjectID = p.ProjectID
LEFT OUTER JOIN tblEmployee AS emp ON mo.OrderedByEmpID = emp.EmployeeID
WHERE mo.OrderID = #OrderID"
DeleteCommand="DELETE FROM tblMatOrder WHERE OrderID = #OrderID"
InsertCommand="INSERT INTO tblMatOrder (OrderDate, ProjectID) VALUES (#OrderDate, #ProjectID);
SELECT #NewOrderID = SCOPE_IDENTITY()"
UpdateCommand="UPDATE tblMatOrder SET OrderDate = #OrderDate, OrderedByEmpID = #OrderedByEmpID,
DateNeeded = #DateNeeded, ReasonID = #ReasonID, Notes = #Notes
WHERE OrderID = #OrderID"
OnInserted="FvMatOrdersSQL_OnInserted">
<SelectParameters>
<asp:RouteParameter Name="OrderID" Type="Int32" RouteKey="OrderID"/>
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="OrderID" Type="Int32" DefaultValue="0"/>
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="OrderDate" Type="DateTime"/>
<asp:Parameter Name="ProjectID" Type="Int32"/>
<asp:Parameter Direction ="Output" Name="NewOrderID" Type="Int32" DefaultValue="0"/>
</InsertParameters>
<UpdateParameters>
<asp:RouteParameter Name="OrderID" Type="Int32" RouteKey="OrderID"/>
<asp:Parameter Name="OrderDate" Type="DateTime"/>
<asp:Parameter Name="OrderedByEmpID" Type="Int32"/>
<asp:Parameter Name="DateNeeded" Type="DateTime"/>
<asp:Parameter Name="ReasonID" Type="Int32"/>
<asp:Parameter Name="Notes" Type="String"/>
</UpdateParameters>
</asp:SqlDataSource>
On Button Click codebehind
protected void FvFooter_OnItemCommand(object sender, FormViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "DeleteOrder":
// Confirmation stuff here
break;
case "NewOrder" when Page.IsValid:
Label lblProjectId = (Label)FvHeader.FindControl("LblProjectID");
String strOrderDate = DateTime.Now.ToShortDateString();
FvMatOrdersSQL.InsertParameters.Clear();
FvMatOrdersSQL.InsertParameters.Add("ProjectID", lblProjectId.Text);
FvMatOrdersSQL.InsertParameters.Add("OrderDate", strOrderDate);
FvMatOrdersSQL.Insert();
break;
case "Email" when Page.IsValid:
break;
}
}
OnInserted codebehind
protected void FvMatOrdersSQL_OnInserted(object sender, SqlDataSourceStatusEventArgs e)
{
String strOrderId = e.Command.Parameters["#NewOrderID"].Value.ToString();
Response.Redirect("MatOrderDetails.aspx?OrderID=" + strOrderId);
}
I've tried to base as much of my code on the example here https://msdn.microsoft.com/en-us/library/ms228051.aspx but apparently I'm missing something.
I've put yr code and have created a db close to yr select to figure out yr problem, I have to admit it wasn't easy :) please
change this
FvMatOrdersSQL.InsertParameters.Clear();
FvMatOrdersSQL.InsertParameters.Add("ProjectID", lblProjectId.Text);
FvMatOrdersSQL.InsertParameters.Add("OrderDate", strOrderDate);
To:
FvMatOrdersSQL.InsertParameters["ProjectID"].DefaultValue = lblProjectId.Text;
FvMatOrdersSQL.InsertParameters["OrderDate"].DefaultValue = strOrderDate;
Don't remove the params which you've already created in the UI!

Can I use the update statement with the select statement together in an SqlDataSource?

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>

Find control in grid view control

I know there are alot of questions&answers about this but non of them works for me
Trying to populate this Drop Down List via a function in code behind:
This drop down list is for Images names, when a user choose one and clicks the "Update" link button in the Grid View I need to insert a suffix to the image name (for the path),
so if the user choose an image name from the list the update button it will actually update the fileName + insert at the beginning the path, so it would be
../images/gary.jpg
for the name gary.
aspx page
<asp:TemplateField>
<EditItemTemplate>
<asp:DropDownList ID="ddlImages" runat="server">
<Items>
<asp:ListItem Text="Choose" Value="" />
</Items>
</asp:DropDownList>
</EditItemTemplate>
...
code behind
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlImages = (e.Row.FindControl("ddlImages") as DropDownList);
ShowImages(ddlImages);
}
}
"ddlImages" is null, how can I find him?
Managed to find the drop down list like that:
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlImages = (DropDownList)e.Row.FindControl("ddlImages");
ddlImages.DataSource = GetImages();
ddlImages.DataBind();
}
}
Now i am facing another problem, in the aspx i have an "UpdateCommand" which take parameters and try to update the database. The problem- it need to take the dropDownList chosen value but instead it take: "" how can i change it to take the value that the user choose in the dropDownList
aspx page
UpdateCommand="UPDATE [investigator] SET [name] = #name, [area] = #area, [country] = #country, [picture] = #picture, [review] = #review WHERE [Id] = #Id">
<UpdateParameters>
<asp:Parameter Name="name" Type="String" />
<asp:Parameter Name="area" Type="String" />
<asp:Parameter Name="country" Type="String" />
<asp:Parameter Name="picture" Type="String" />
<asp:Parameter Name="review" Type="String" />
<asp:Parameter Name="Id" Type="Int32" />
</UpdateParameters>
Meaning- I have to change
<asp:Parameter Name="picture" Type="String" />
to drop down list selected value. How can I achieve that?
Regarding your question about the update Parameter, you should use the ControlParameter instead of general Parameter. Try replacing the Parameter Definition for the Dropdown list with following
code.
<asp:ControlParameter Name="picture" ControlID="ddlImages"
PropertyName="SelectedValue" Type="String" />
UPDATE
What you can do as alternate is,
Change the parameter back to
<asp:Parameter Name="picture" Type="String" />
Add RowUpdating event handler to the gridview
In the RowUpdating command set the data source parameter based on the selected value as below
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
DropDownList ddlImages= row.FindControl("ddlImages") as DropDownList;
SqlDataSource1.UpdateParameters["picture"].DefaultValue = ddlImages.SelectedValue;
}

Get ID in insert command asp and use it in code behind c#

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));
}
}

Converted from SqlDataSource to ObjectDataSource, causing grief

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

Categories