将所选图像从gridview插入到db中

时间:2016-08-04 10:12:21

标签: c# asp.net gridview

我想将gridview中的选定图像插入到mysql表中。当我尝试时,它给我的消息说

  

发生了类型为“ System.InvalidCastException ”的异常   App_Web_zptg3ta3.dll但未在用户代码中处理。额外   信息:无法将“ System.Int32 ”类型的对象强制转换为类型   '的System.Data.DataRow'。

以下是我的c#&标记代码:

if (gvImages.SelectedIndex != -1)
{
    DataRow SelectedRowValue = ((DataRow)gvImages.SelectedValue);
byte[] ImageBytes = (byte[])SelectedRowValue.ItemArray[1];
MySqlCommand cmd2 = new MySqlCommand("INSERT INTO rasmlar (Rasm) VALUES (@ImageSource)", con);
cmd2.Parameters.Add("@ImageSource", MySqlDbType.Blob, ImageBytes.Length).Value = ImageBytes;
    cmd2.ExecuteNonQuery();
}

<asp:GridView ID="gvImages" runat="server" OnRowDataBound="OnRowDataBound" 
                        DataKeyNames="Rasm_ID" AutoGenerateSelectButton="True" AllowPaging="True" 
                        AutoGenerateColumns="False" OnPageIndexChanging="gvImages_PageIndexChanging" 
                        PageSize="5" SelectedIndex="1">
                       <Columns>
                            <asp:TemplateField HeaderText="Rasm_ID">
                                <EditItemTemplate>
                                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Rasm_ID") %>'></asp:TextBox>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Rasm_ID") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Rasm">
                                <ItemTemplate>
                                    <asp:Image ID="Image1" runat="server" Height="80" Width="80" />
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                        <selectedrowstyle backcolor="LightCyan" forecolor="DarkBlue" font-bold="true"/>                           
                        </asp:GridView> 

1 个答案:

答案 0 :(得分:0)

你的很多代码看起来都不正确。从:

开始
DataRow SelectedRowValue = ((DataRow)gvImages.SelectedValue);

GridView.SelectedValue不是你想要的。我相信你想要GridView.SelectedRow

GridViewRow row = gvImages.SelectedRow;

// Change `.Cells[5]` to the correct cell index.
byte[] imageAsBytes = (byte[])row.Cells[5].Value;
MemoryStream ms = new MemoryStream();
Image i = Image.FromStream(ms);