如何从GridView编辑图像

时间:2015-11-13 09:05:49

标签: c# asp.net gridview

这是我的aspx:

<td>
   <asp:FileUpload ID="fileupload" runat="server" />  
</td>

CS:

这是为了插入:

SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("@Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("@Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("@Address", Textaddress.Text.Trim());
try
{
     string filename = Path.GetFileName(fileupload.PostedFile.FileName);
     fileupload.SaveAs(Server.MapPath("~/Images/" + filename));                   
     com.Parameters.AddWithValue("@Image", "Images/" + filename);
     com.ExecuteNonQuery();
     Response.Redirect("studententry.aspx");
}
catch (Exception ex)
{
     btnsub.Text = ex.Message;
}

插入所有详细信息后,它显示为this

这是从gridview编辑的:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
     SqlConnection con = Connection.DBconnection();
     if (e.CommandName == "EditRow")
     {
         GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
         int index = gr.RowIndex; 
         hiddenfield.Value = index.ToString(); 
         Textid.Text = gr.Cells[0].Text;
         Textusername.Text = gr.Cells[1].Text;
         Textclass.Text = gr.Cells[2].Text;
         Textsection.Text = gr.Cells[3].Text;
         Textaddress.Text = gr.Cells[4].Text;               
     }
}

当我从GridView编辑特定行时,它会编辑预期图像。

因此图像不可编辑。我可以知道如何编辑图像吗?

1 个答案:

答案 0 :(得分:0)

试试这个,

首先在Gridview控件内的图像控件旁边添加2个隐藏(hd_gv,hd_update)字段,然后在窗体中添加其他字段,并使用图像src设置隐藏字段值。

现在在Gridview_RowCommand 获取 src和设置 hd_update隐藏字段值,所以你的代码看起来像这样

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    SqlConnection con = Connection.DBconnection();
    if (e.CommandName == "EditRow")
    {

       GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
        HiddenField imgSRC = (HiddenField)row.FindControl("hd_gv");
        hd_update.Value=imgSRC.Value;
    }

现在在你的更新函数上首先检查Fileupload控件是否有任何文件,如果是,然后上传文件并用新上传文件更新图像src,否则设置hd_update(隐藏字段)值。

按钮单击

时更新代码如下所示
string Filename = hd_update.Value; // "HIDDEN_FIELD_IMAGE_SRC";
if (fileupload.HasFile)
{
     //code to upload and set Filename variable with new file
     Filename="NEW FILE NAME";
}

<强> Some useful Gridview Articles