在insert命令asp中获取ID并在c#后面的代码中使用它

时间:2014-06-09 00:30:58

标签: c# asp.net insert

我有一个listview

    <asp:ListView ID="ListViewNews" runat="server" DataSourceID="SqlDataSourceAddNews" DataKeyNames="Id" InsertItemPosition="LastItem" OnItemCommand="ListViewNews_ItemCommand">
    <InsertItemTemplate>
    <asp:FileUpload ID="FileUpload2" runat="server" />
    </InsertItemTemplate>

和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>

我想获取插入命令的ID来命名上传的照片

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

想知道如何在这里获取ID的简单解决方案吗?

1 个答案:

答案 0 :(得分:3)

试试这个,

将您的插入命令更改为:

InsertCommand="INSERT INTO News(TITLE, SUMMARY, TEXT, DATETIME, PHOTO, [FILE])
               VALUES (@TITLE, @SUMMARY, @TEXT, @DATETIME, @PHOTO, @FILE);
               SELECT @Id = SCOPE_IDENTITY();" 

将新输出参数添加到InsertParameters列表

<asp:Paramter Direction="Output" Name="Id" Type="Int32" />

将您的文件保存代码移至SQLDataSource Inserted方法,您无法直接在ItemCommand事件中访问此生成的ID

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