gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:05:50 25 4
gpt4 key购买 nike

我有一个 ListView

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

和 sql 数据源:

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

我想获取insert命令的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 的简单解决方案有什么想法吗?

最佳答案

试试这个,

将您的插入命令更改为:

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

关于c# - 在插入命令asp中获取ID并在c#后面的代码中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24112267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com