列或单元格中选择特定值

列或单元格中选择特定值

本文介绍了从gridview中的任何行,列或单元格中选择特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个gridview,其中有两个数据库表显示的信息。我想从业务名称列中选择业务名称,并根据用户选择viewfile的行从单元格中选择值,并将其分配给字符串变量。



这是我的代码(请注意,在点击'搜索内容'按钮后,page_load上没有显示gridview)



I have a gridview of which there is information displayed from two database tables. I want to select the business name from the "Business name" column and the value from the cell based on the row that the user selects 'viewfile' and assign it to a string variable.

Here is my code(note the gridview is not displayed on the page_load but after a 'search content' button is clicked)

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            try
            {
                switch (e.CommandName)
                {

                    case "view":

                        String name = GridView1.Rows[4].Cells[4].FindControl("Business_Name").ToString(); 
                        string filename = e.CommandArgument.ToString();
                        string path = Server.MapPath("~/BusinessProfilesContent/" + name + "/" + filename);
                        byte[] bts = System.IO.File.ReadAllBytes(path);
                        Response.Clear();
                        Response.ClearHeaders();
                        Response.ContentType = "image";
                        Response.WriteFile(path);
                        Response.Flush();
                        Response.End();
                        break;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);

            }
        }





这是webform代码:





Here is the webform code:

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 

                        EmptyDataText = "No files uploaded" Width="766px" onrowcommand="GridView1_RowCommand">
    <Columns>
       <asp:BoundField DataField = "Incident_ID" HeaderText = "Incident ID" />
       <asp:BoundField DataField = "Incident_Type_Name" HeaderText = "Incident Type" />
       <asp:BoundField DataField = "Description" HeaderText = "Description" />
       <asp:BoundField DataField = "Date_Time" HeaderText = "Date and time of Upload" />
       <asp:BoundField DataField = "Business_Name" HeaderText = "Business Name" />
       <asp:BoundField DataField = "Provence" HeaderText = "Provence" />
       <asp:BoundField DataField = "County" HeaderText = "County" />
       <asp:BoundField DataField = "Username" HeaderText = "Username" />
       <asp:ImageField DataImageUrlField="File_Path" ControlStyle-Width="100"

        ControlStyle-Height = "100" HeaderText = "Preview Image"/>
        <asp:TemplateField ItemStyle-HorizontalAlign = "Center">
            <ItemTemplate>
               <asp:LinkButton ID="LinkButton1"  runat="server" CausesValidation="false" CommandName="view" CommandArgument = '<%#Eval("FileName")%>' >ViewFile</asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

推荐答案

引用:

对象引用未设置为对象的实例

object reference not set to an instance of an object



我认为是这行触发该异常


I think it is this line that is firing that exception

String name = GridView1.Rows[4].Cells[4].FindControl("Business_Name").ToString();



首先,我认为你不需要 .FindControl(商业名称) - 你没有一个名为的控件那 - 它是你的一个列的标题......实际上是列索引4.

其次,你总是在数据网格上查看行索引4 ...如果你还没有那里有5排?

这两个问题都可能产生错误。



现在解决它...

那个参数 GridViewCommandEventArgs e 派上用场找到被选中的行...


Firstly, I don't think you need the .FindControl("Business Name") - you don't have a control called that - it's the title of one of your columns... column index 4 in fact.
Secondly, you are always looking at row index 4 on your datagrid ... what if you haven't got 5 rows in there?
Both of these issues could have produced that error.

Now to solve it ...
That parameter GridViewCommandEventArgs e comes in handy for finding the row that was selected...

int i = Convert.ToInt32(e.CommandArgument);
GridViewRow r = GridView1.Rows[i];



接下来你想要的是与商业名称栏对应的单元格 - 我已经知道这是列索引4所以你的代码变成


Next you want the cell that corresponds to the "Business Name" column - I already know that this is column index 4 so your code becomes

String name = r.Cells[4].Text;



如果你不想硬编码列号(你不应该想看) []根据名称获取列


If you don't want to Hard-Code the column number (and you shouldn't want to) have a look at this post on StackOverflow[^] to get the column based on its name


protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {


            try
            {
                switch (e.CommandName)
                {

                    case "view":

                        LinkButton l = e.CommandSource as LinkButton;

                        GridViewRow selectedRow = l.NamingContainer as GridViewRow ;

                        int intRowIndex = Convert.ToInt32(selectedRow.RowIndex);

                        GridViewRow row = GridView1.Rows[intRowIndex];
                        String name = Server.HtmlDecode(row.Cells[4].Text);
                        string filename = e.CommandArgument.ToString();
                        String ext = String.Empty;
                        string path = Server.MapPath("~/BusinessProfilesContent/" + name + "/" + filename);
                        SqlConnection conn;
                        SqlCommand comm;
                        String connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
                        conn = new SqlConnection(connectionString);
                        comm = new SqlCommand("SELECT Incident.File_Extension FROM Incident	JOIN User_Acc ON user_acc.User_id=incident.user_id JOIN business ON incident.business_id=business.Business_id JOIN incident_type ON incident_type.incident_type_id = incident.incident_type_id WHERE Business.Business_Name = Business.Business_Name AND Incident.FileName=@FileName", conn);
                         comm.Parameters.Add("@FileName", System.Data.SqlDbType.VarChar).Value = e.CommandArgument;
                        conn.Open();
                        SqlDataReader reader = comm.ExecuteReader();
                        while (reader.Read())
                        {
                          ext = reader["File_Extension"].ToString();
                        }
                        byte[] bts = System.IO.File.ReadAllBytes(path);
                        Response.Clear();
                        Response.ClearHeaders();
                        if (ext.Equals(".mov", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/quicktime";
                        }
                        else if (ext.Equals(".jpg", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "image/jpeg";
                        }
                        else if (ext.Equals(".jpeg", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "image/jpeg";
                        }
                        else if (ext.Equals(".gif", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "image/gif";
                        }
                        else if (ext.Equals(".mp2", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/mpeg";
                        }
                        else if (ext.Equals(".mpa", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/mpeg";
                        }
                        else if (ext.Equals(".mpe", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/mpeg";
                        }
                        else if (ext.Equals(".mpeg", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/mpeg";
                        }
                        else if (ext.Equals(".mpg", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/mpeg";
                        }
                        else if (ext.Equals(".mpv2", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/mpeg";
                        }
                        else if (ext.Equals(".qt", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/quicktime";
                        }
                        else if (ext.Equals(".avi", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Response.ContentType = "video/x-msvideo";
                        }
                        Response.WriteFile(path);
                        Response.Flush();
                        Response.End();
                        break;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);

            }
        }


这篇关于从gridview中的任何行,列或单元格中选择特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 16:55