asp.net中的GridView如何加入FileUpload按钮?

yourname888 2012-10-16 10:16:02
asp.net中的GridView如何加入FileUpload按钮?并实现上传图片(图片要重命名的)然后点自带的【更新按钮】把图片路径保存到数据库里?
数据库表列 ID UserName UserImage

哪位朋友帮忙写个完整代码啊 谢谢了~!
...全文
365 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wjxluck 2012-12-10
  • 打赏
  • 举报
回复
添加一个模板列,里面放个upload
javamy025 2012-12-09
  • 打赏
  • 举报
回复
支持下,加油楼主
孟子E章 2012-10-16
  • 打赏
  • 举报
回复

private int EditId = 0;
private String ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\ASPNET20Book.mdb;";


/// 显示图片,在图片不存在时显示一个 none.gif

private string GetUserPhoto(object pathPhoto)
{
if (pathPhoto == DBNull.Value)
{
return "<img src='Images/none.gif'>";
}
else
{
return "<img src='" + pathPhoto.ToString() + "'>";
}
}


/// <summary>
/// 数据绑定的处理。在需要编辑时,显示出编辑框
/// </summary>

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (EditId > 0)
{
//如果绑定数据源是DatarReader,则使用下面的方法:
//System.Data.Common.DbDataRecord rowItem = (System.Data.Common.DbDataRecord)e.Row.DataItem;

//如果绑定是 DataView,则使用此方法
System.Data.DataRowView rowItem = (System.Data.DataRowView)e.Row.DataItem;
if (rowItem["id"].ToString().Equals(EditId.ToString()))
{
//隐藏显示的文字
PlaceHolder LabelTitle = e.Row.FindControl("LabelTitle") as PlaceHolder;
LabelTitle.Visible = false;
PlaceHolder LabelBirthday = e.Row.FindControl("LabelBirthday") as PlaceHolder;
LabelBirthday.Visible = false;
PlaceHolder LabelGender = e.Row.FindControl("LabelGender") as PlaceHolder;
LabelGender.Visible = false;
PlaceHolder LabelClassName = e.Row.FindControl("LabelClassName") as PlaceHolder;
LabelClassName.Visible = false;
PlaceHolder LabelPhoto = e.Row.FindControl("LabelPhoto") as PlaceHolder;
LabelPhoto.Visible = false;

//打开编辑框
TextBox uTitle = e.Row.FindControl("uTitle") as TextBox;
uTitle.Visible = true;

TextBox uBirthDay = e.Row.FindControl("uBirthDay") as TextBox;
uBirthDay.Visible = true;

RadioButtonList uGender = e.Row.FindControl("uGender") as RadioButtonList;
uGender.Visible = true;

DropDownList uClassName = e.Row.FindControl("uClassName") as DropDownList;
uClassName.Visible = true;

FileUpload uPhoto = e.Row.FindControl("uPhoto") as FileUpload;
uPhoto.Visible = true;

//赋原来的值
if (rowItem["Gender"] != DBNull.Value)
{
uGender.SelectedIndex = (Convert.ToBoolean(rowItem["Gender"]) ? 0 : 1);
}

if (rowItem["ClassName"] != DBNull.Value)
{
uClassName.Items.FindByText(rowItem["ClassName"].ToString()).Selected = true;
}

//显示编辑更新按钮
Panel PanelNormal = e.Row.FindControl("PanelNormal") as Panel;
PanelNormal.Visible = false;

Panel PanelUpdate = e.Row.FindControl("PanelUpdate") as Panel;
PanelUpdate.Visible = true;
}
}
}
}

/// <summary>
/// 打开编辑框,将编辑标识传递到 EditId
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void EditClick(object sender, EventArgs e)
{
Button b = sender as Button;
EditId = Convert.ToInt32(b.CommandArgument);

GridViewRow dvr = b.NamingContainer as GridViewRow;
EditId = (int)GridView1.DataKeys[dvr.DataItemIndex].Value;
DataBind();
//Response.Write(GridView1.DataKeys[dvr.DataItemIndex].Value);

}


protected void UpdateClick(object sender, EventArgs e)
{
Button b = sender as Button;
GridViewRow dvr = b.NamingContainer as GridViewRow;
TextBox uTitle = dvr.FindControl("uTitle") as TextBox;

string StudentTitle = uTitle.Text;
string StudentBirthDay = ((TextBox)dvr.FindControl("uBirthDay")).Text;
bool StudentGender = ((RadioButtonList)dvr.FindControl("uGender")).SelectedValue == "男" ? true : false;
string StudentClassName = ((DropDownList)dvr.FindControl("uClassName")).SelectedValue;
string StudentID = GridView1.DataKeys[dvr.RowIndex].Value.ToString();
string sql = "";
String PhotoPath = "";
bool HasFileUploaded = false;

FileUpload oUpload = (FileUpload)dvr.FindControl("uPhoto");
if (oUpload.HasFile)
{
PhotoPath = Guid.NewGuid().ToString("D") + System.IO.Path.GetExtension(oUpload.FileName);
oUpload.SaveAs(Server.MapPath("~") + "\\" + PhotoPath);
HasFileUploaded = true;
}

if (HasFileUploaded)
{
sql = "Update Student Set Title=@Title,BirthDay = @BirthDay,";
sql += "Gender=@Gender,PhotoPath=@PhotoPath,ClassName=@ClassName Where id=@id";
}
else
{
sql = "Update Student Set Title=@Title,BirthDay = @BirthDay,";
sql += "Gender=@Gender,ClassName=@ClassName Where id=@id";
}

OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand(sql, cn);

cmd.Parameters.AddWithValue("@Title", StudentTitle);
cmd.Parameters.AddWithValue("@BirthDay", StudentBirthDay);
cmd.Parameters.AddWithValue("@Gender", StudentGender);
if (HasFileUploaded)
{
cmd.Parameters.AddWithValue("@PhotoPath", PhotoPath);
}
cmd.Parameters.AddWithValue("@ClassName", StudentClassName);
cmd.Parameters.AddWithValue("@id", StudentID);
cmd.ExecuteNonQuery();
cn.Close();

Response.Redirect(Request.Url.ToString());

}


/// <summary>
/// 添加新记录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void AddClick(object sender, EventArgs e)
{
InsertNewRecord(sender, e);
}

/// <summary>
/// 取消编辑
/// </summary>
protected void CancelClick(object sender, EventArgs e)
{
Response.Redirect(Request.UrlReferrer.ToString());
}

/// <summary>
/// 删除记录
/// </summary>
protected void DeleteClick(object sender, EventArgs e)
{
Button b = sender as Button;
int id = Convert.ToInt32(b.CommandArgument);
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand("Delete From [Student] Where [id]=@id", cn);
cmd.Parameters.AddWithValue("@id", id);
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.Url.ToString());
}

/// <summary>
/// 插入新记录的公共函数
/// </summary>
protected void InsertNewRecord(object sender, EventArgs e)
{
string StudentTitle = ((TextBox)(sender as Button).NamingContainer.FindControl("NewTitle")).Text;
if (StudentTitle.Trim() == "")
{
ErrorMsg.Text = "请输入姓名";
return;
}
string StudentBirthDay = ((TextBox)(sender as Button).NamingContainer.FindControl("NewBirthDay")).Text;
bool StudentGender = ((RadioButtonList)
(sender as Button).NamingContainer.FindControl("NewGender")).SelectedValue == "男" ? true : false;
string StudentClassName = ((DropDownList)
(sender as Button).NamingContainer.FindControl("NewClassName")).SelectedValue;
FileUpload oUpload = (FileUpload)(sender as Button).NamingContainer.FindControl("AddPhoto");
String FileName = "";
FileName = Guid.NewGuid().ToString("D") + System.IO.Path.GetExtension(oUpload.FileName);
oUpload.SaveAs(Server.MapPath("~") + "\\" + FileName);
string sql = "Insert Into Student (Title,BirthDay,Gender,PhotoPath,ClassName)";
sql += " Values(@Title,@BirthDay,@Gender,@PhotoPath,@ClassName)";
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();

OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.Parameters.AddWithValue("@Title", StudentTitle);
cmd.Parameters.AddWithValue("@BirthDay", StudentBirthDay);
cmd.Parameters.AddWithValue("@Gender", StudentGender);
cmd.Parameters.AddWithValue("@PhotoPath", FileName);
cmd.Parameters.AddWithValue("@ClassName", StudentClassName);

cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect(Request.FilePath.ToString());
}


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataBind();
}
}


protected void DataBind()
{
OleDbCommand cmd;
String sql;
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();


sql = "SELECT * FROM [Student] ORDER BY [id] DESC";

OleDbDataAdapter da = new OleDbDataAdapter(sql, cn);
DataSet ds = new DataSet();
da.Fill(ds,"Student");

GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
cn.Close();

}
心灵彩虹 2012-10-16
  • 打赏
  • 举报
回复

上传http://www.cnblogs.com/qiantuwuliang/archive/2009/08/21/1551200.html

/// <summary>
/// 获取一个图片按等比例缩小后的大小。
/// </summary>
/// <param name="maxWidth">需要缩小到的宽度</param>
/// <param name="maxHeight">需要缩小到的高度</param>
/// <param name="imageOriginalWidth">图片的原始宽度</param>
/// <param name="imageOriginalHeight">图片的原始高度</param>
/// <returns>返回图片按等比例缩小后的实际大小</returns>
public static Size GetNewSize(int maxWidth, int maxHeight, int imageOriginalWidth, int imageOriginalHeight)
{
double w = 0.0;
double h = 0.0;
double sw = Convert.ToDouble(imageOriginalWidth);
double sh = Convert.ToDouble(imageOriginalHeight);
double mw = Convert.ToDouble(maxWidth);
double mh = Convert.ToDouble(maxHeight);

if (sw < mw && sh < mh)
{
w = sw;
h = sh;
}
else if ((sw / sh) > (mw / mh))
{
w = maxWidth;
h = (w * sh) / sw;
}
else
{
h = maxHeight;
w = (h * sw) / sh;
}

return new Size(Convert.ToInt32(w), Convert.ToInt32(h));
}
孟子E章 2012-10-16
  • 打赏
  • 举报
回复
完整的源代码:
ASPX 代码

<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>GridView 插入、删除、修改的例子</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
OnRowDataBound="GridView1_RowDataBound" ShowFooter="true">
<HeaderStyle BackColor="#ccff99" Font-Bold="true" />
<Columns>
<asp:TemplateField HeaderText="姓名">
<ItemTemplate>
<asp:PlaceHolder ID="LabelTitle" runat="server">
<%#Eval("Title") %></asp:PlaceHolder>
<asp:TextBox ID="uTitle" runat="server" Text='<%#Eval("Title") %>' Visible="false"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NewTitle" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="生日(yyyy-MM-dd格式)">
<ItemTemplate>
<asp:PlaceHolder ID="LabelBirthday" runat="server">
<%#Eval("BirthDay", "{0:yyyy-MM-dd}")%></asp:PlaceHolder>
<asp:TextBox ID="uBirthDay" runat="server" Text='<%#Eval("BirthDay", "{0:yyyy-MM-dd}")%> '
Visible="false" />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NewBirthDay" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="性别">
<ItemTemplate>
<asp:PlaceHolder ID="LabelGender" runat="server">
<%#(Eval("Gender")).ToString() =="True"?"男":"女"%></asp:PlaceHolder>
<asp:RadioButtonList ID="uGender" runat="server" RepeatDirection="Horizontal" Visible="false">
<asp:ListItem Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
<FooterTemplate>
<asp:RadioButtonList ID="NewGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="true" Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="年级">
<ItemTemplate>
<asp:PlaceHolder ID="LabelClassName" runat="server">
<%#Eval("ClassName")%></asp:PlaceHolder>
<asp:DropDownList ID="uClassName" runat="server" Visible="false">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="NewClassName" runat="server">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="照片">
<ItemTemplate>
<asp:PlaceHolder ID="LabelPhoto" runat="server">
<%# GetUserPhoto(Eval("PhotoPath")) %></asp:PlaceHolder>
<asp:FileUpload ID="uPhoto" runat="server" Visible="false" />
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="AddPhoto" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="操作">
<ItemTemplate>
<asp:Panel ID="PanelNormal" runat="server">
<asp:Button ID="EditButton" runat="server" Text="修改" OnClick="EditClick" CommandArgument='<%#Eval("id") %>' />
<asp:Button ID="DeleteButton" runat="server" Text="删除" OnClick="DeleteClick" CommandArgument='<%#Eval("id") %>' />
</asp:Panel>
<asp:Panel ID="PanelUpdate" runat="server" Visible="false">
<asp:Button ID="UpdateButton" runat="server" Text="更新" OnClick="UpdateClick" CommandArgument='<%#Eval("id") %>' />
<asp:Button ID="CancelButton" runat="server" Text="取消" OnClick="CancelClick" />
</asp:Panel>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="AddButton" runat="server" Text="添加新纪录" OnClick="AddClick" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<table cellspacing="0" rules="all" border="1" style="border-collapse: collapse;">
<tr>
<th>姓名</th>
<th>生日(yyyy-MM-dd格式)</th>
<th>性别</th>
<th>年级</th>
<th>照片</th>
<th>操作</th>
</tr>
<tr>
<td>
<asp:TextBox ID="NewTitle" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="NewBirthDay" runat="server"></asp:TextBox>
</td>
<td>
<asp:RadioButtonList ID="NewGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="true" Text="男"></asp:ListItem>
<asp:ListItem Text="女"></asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:DropDownList ID="NewClassName" runat="server">
<asp:ListItem Text="小学" Value="小学"></asp:ListItem>
<asp:ListItem Text="中学" Value="中学"></asp:ListItem>
<asp:ListItem Text="高中" Value="高中"></asp:ListItem>
<asp:ListItem Text="大学" Value="大学"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:FileUpload ID="AddPhoto" runat="server" />
</td>
<td>
<asp:Button ID="b" runat="server" Text="添加学生" OnClick="AddClick" />
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>
<div id="Pager" runat="server" style="text-align:left;padding:10px 0;"></div>
<asp:Label ID="ErrorMsg" runat="server" ForeColor="red"></asp:Label>
</form>
</body>
</html>

61,653

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧