I have make a gridview with object data source. I make a class for the Object Data Source and make the gridview in aspx page.
It was run perfectly, but i want to make, when i update the table, there is two coloumn that will turn into dropdownlist, not free text.
I dont know how to make that, can you make/give me some example.
This is my Object Data Source Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace quittance.Kelas
{
public class dalamkota_rincian_8:daftarproperti
{
public static List<daftarproperti> AmbilJadwal(string nomorSt)
{
List<daftarproperti> Listjadwal = new List<daftarproperti>();
string CS = ConfigurationManager.ConnectionStrings["nikita_app"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("xp_generatejadwal_dalamkota8", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramnoSt = new SqlParameter("#nomorSt", nomorSt);
cmd.Parameters.Add(paramnoSt);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
daftarproperti jadwal = new daftarproperti();
jadwal.tugasID = (int)rdr["tugasID"];
jadwal.nama = rdr["nama"].ToString();
jadwal.nip = rdr["nip"].ToString();
jadwal.gol = rdr["gol"].ToString();
jadwal.tgl_mulai = rdr["tgl_mulai"].ToString();
jadwal.tgl_selesai = rdr["tgl_selesai"].ToString();
jadwal.jumlahhari1 = rdr["jumlahhari1"] as int? ?? default(int);
Listjadwal.Add(jadwal);
}
}
return Listjadwal;
}
}
}
The Object Data Source and the Gridview has been connected.
<asp:ObjectDataSource ID="ds_dalamkota8_jadwal" runat="server" DeleteMethod="DeleteJadwal" InsertMethod="InsertJadwal" SelectMethod="AmbilJadwal" TypeName="quittance.Kelas.dalamkota_rincian_8" UpdateMethod="UpdateJadwal">
<DeleteParameters>
<asp:Parameter Name="tugasID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="nip" Type="String" />
<asp:Parameter Name="gol" Type="String" />
<asp:Parameter Name="kdlokasi" Type="Int32" />
<asp:Parameter Name="tgl_mulai" Type="String" />
<asp:Parameter Name="tgl_selesai" Type="String" />
</InsertParameters>
<SelectParameters>
<asp:SessionParameter Name="nomorSt" SessionField="nomorst" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="tugasID" Type="Int32" />
<asp:Parameter Name="nip" Type="String" />
<asp:Parameter Name="gol" Type="String" />
<asp:Parameter Name="kdlokasi" Type="Int32" />
<asp:Parameter Name="tgl_mulai" Type="String" />
<asp:Parameter Name="tgl_selesai" Type="String" />
</UpdateParameters>
</asp:ObjectDataSource>
I want to make the nip and gol coloumn turn into dropdownlist when i edit that. I dont know how to make it with object data source, should i make in Object Data Source class or in aspx.cs page with sqldatasource.
Please give me an example/explanation.
you can call the method one which provide data from the page load event then you a can bind data to drop down
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = AmbilJadwal(nomorSt);
GridView1.DataBind();
}
}
Help link is given below most likely it will solve your problem
Bind DropDownList in ItemTemplate of TemplateField in ASP.Net GridView
I've searched around for a while and tried all the different solutions but I can't seem to get the database updated.
I've executed the stored procedure on its own through SSMS and it works fine.
Here's my asp settings:
<asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" UpdateCommand="spProofStamp" UpdateCommandType="StoredProcedure">
<UpdateParameters>
<asp:Parameter Name="sID" Type="String" />
<asp:Parameter Name="UserID" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
Button:
<dx:LayoutItem Caption="">
<LayoutItemNestedControlCollection>
<dx:LayoutItemNestedControlContainer ID="LayoutItemNestedControlContainer1" runat="server">
<dx:ASPxButton ID="ASPxFormLayout2_E2" OnClick="Button1_Click" runat="server" Text="Validate" AutoPostBack="false">
<ClientSideEvents Click="function(s,e){validate();}" />
</dx:ASPxButton>
</dx:LayoutItemNestedControlContainer>
</LayoutItemNestedControlCollection>
</dx:LayoutItem>
My code behind (I've tried databind and update separately as well).
I've also traced through the values and they're all there, how can I tell if the Update/DataBind works or not? Other Databinds within my code are working fine:
protected void Button1_Click(object sender, EventArgs e)
{
SqlDataSource5.UpdateCommandType = SqlDataSourceCommandType.StoredProcedure;
SqlDataSource5.UpdateCommand = "spProofStamp";
SqlDataSource5.UpdateParameters["sID"].DefaultValue = selectedValue;
SqlDataSource5.UpdateParameters["UserID"].DefaultValue = login.ToUpper();
SqlDataSource5.Update();
SqlDataSource5.DataBind();
}
StoredProcedure:
ALTER PROCEDURE [dbo].[spProofStamp]
#UserID nvarchar(15),
#sID nvarchar(15)
AS
SET NOCOUNT ON
UPDATE [dbo].[ORDER]
SET [USERID] = #UserID,
[DATE] = CURRENT_TIMESTAMP
WHERE ID = #sID
I would like to recommend you to change your method from sqldatasource to code behind, as it makes your code more clear and it is more effective.
You may use the next method:
protected void UpdateDB(string user_id, string sid){
SqlConnection con = new SqlConnection(your_connection_string);
SqlCommand cmd = new SqlCommand("spProofStamp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#USERID", SqlDbType.NVarChar).Value = user_id;
cmd.Parameters.Add("#SID", SqlDbType.NVarChar).Value = sid;
try{
con.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex){
//process your exception
}
finally{
con.Close();
Response.Redirect(Request.Url.AbsoluteUri); //refresh this page
}
}
And call your method:
UpdateDB(login.ToUpper(), selectedValue);
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 attempting to return the ID of the newly created row. I've tried doing it with SCOPE_IDENTITY, but it returns a 3. I've searched around and can't determine what I'm doing incorrect.
Here is the code:
<asp:SqlDataSource ID="sourceRecruit" runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$ ConnectionStrings:DBCS %>"
SelectCommand="SELECT * FROM [Players] WHERE ([ID] = #ID)"
UpdateCommand="UPDATE [Players] SET [FirstName] = #FirstName, [LastName]=#LastName, [Height]=#Height, [Weight]=#Weight, [FortyYardDash] = #FortyYardDash, [CombineVerified] = #CombineVerified, [HomeNumber] = #HomeNumber, [CellNumber] = #CellNumber, [Email] = #Email, [Position] = #Position, [Commitment] = #Commitment, [GraduationYear] = #GraduationYear, [LastUpdate] = #LastUpdate, [NetworkUpdate] = #NetworkUpdate, [DecisionDate] = #DecisionDate, [MiscContact] = #MiscContact, [RivalsID] = #RivalsID, [ScoutID] = #ScoutID, [ESPNID] = #ESPNID, [t247SportsID] = #t247SportsID, [PictureID] = #PictureID, [StarRating] = #StarRating, [NationalHot100Rank] = #NationalHot100Rank, [PositionRank] = #PositionRank, [JanuaryEnrollee] = #JanuaryEnrollee, [Recruiter] = #Recruiter, [RecruitedPosition] = #RecruitedPosition, [SummerCamp] = #SummerCamp, [JuniorDay] = #JuniorDay, [SpringGame] = #SpringGame, [UnofficialVisit] = #UnofficialVisit, [FootballGame] = #FootballGame, [OfficialVisitDate] = #OfficialVisitDate, [Status] = #Status, [Updates] = #Updates, [Favorites] = #Favorites, [Visits] = #Visits, [Odds] = #Odds WHERE [ID] = #ID"
InsertCommand="INSERT INTO Players ([FirstName], [LastName], [Height], [Weight], [FortyYardDash], [CombineVerified], [HomeNumber], [CellNumber], [Email], [Position], [Commitment], [GraduationYear], [LastUpdate], [NetworkUpdate], [DecisionDate], [MiscContact], [RivalsID], [ScoutID], [ESPNID], [t247SportsID], [PictureID], [StarRating], [NationalHot100Rank], [PositionRank], [JanuaryEnrollee], [Recruiter], [RecruitedPosition], [SummerCamp], [JuniorDay], [SpringGame], [UnofficialVisit], [FootballGame], [OfficialVisitDate], [Status], [Updates], [Favorites], [Visits], [Odds]) VALUES (#FirstName, #LastName, #Height, #Weight, #FortyYardDash, #CombineVerified, #HomeNumber, #CellNumber, #Email, #Position, #Commitment, #GraduationYear, #LastUpdate, #NetworkUpdate, #DecisionDate, #MiscContact, #RivalsID, #ScoutID, #ESPNID, #t247SportsID, #PictureID, #StarRating, #NationalHot100Rank, #PositionRank, #JanuaryEnrollee, #Recruiter, #RecruitedPosition, #SummerCamp, #JuniorDay, #SpringGame, #UnofficialVisit, #FootballGame, #OfficialVisitDate, #Status, #Updates, #Favorites, #Visits, #Odds); SET #ID=SCOPE_IDENTITY()"
OnInserted="reloadPage">
<SelectParameters>
<asp:QueryStringParameter QueryStringField="ID" Name="ID" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="DecisionDate" ConvertEmptyStringToNull="true" />
<asp:Parameter Name="NetworkUpdate" ConvertEmptyStringToNull="true" />
<asp:Parameter Name="OfficialVisitDate" ConvertEmptyStringToNull="true" />
<asp:Parameter Name="LastUpdate" ConvertEmptyStringToNull="true" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="ID" DefaultValue="Int32" Direction="Output" />
<asp:Parameter Name="DecisionDate" ConvertEmptyStringToNull="true" />
<asp:Parameter Name="NetworkUpdate" ConvertEmptyStringToNull="true" />
<asp:Parameter Name="OfficialVisitDate" ConvertEmptyStringToNull="true" />
<asp:Parameter Name="LastUpdate" ConvertEmptyStringToNull="true" />
</InsertParameters>
</asp:SqlDataSource>
Here is my code behind:
protected void reloadPage(object sender, SqlDataSourceStatusEventArgs e)
{
object newid = e.Command.Parameters["#ID"].Value;
lblResults.Text = "Test "+Convert.ToString(newid);
}
Like I've mentioned, every time I've ran the code, lblResults displays a "3," but the ID is in the 3000 range.
You need to use the OnInserted event, and specify the output direction of the parameter:
<asp:Parameter Direction="Output" Name="ID" Type="Int32" />
Code-behind:
protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
int id = Convert.ToInt32(e.Command.Parameter["#ID"].Value);
}
I also noticed that you set DefaultValue="Int32". You should change that to Type="Int32".
If you still have problems after applying the above changes, try changing SET #ID = SCOPE_IDENTITY to SELECT #ID = SCOPE_IDENTITY. Shouldn't make a difference, but if all else fails...
Did you try
SELECT #ID = SCOPE_IDENTITY()
instead of
SET #ID = SCOPE_IDENTITY()
that is what I have and works perfect.
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