Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ASP.NET c#模板字段中的复选框列表_C#_Asp.net_Gridview - Fatal编程技术网

ASP.NET c#模板字段中的复选框列表

ASP.NET c#模板字段中的复选框列表,c#,asp.net,gridview,C#,Asp.net,Gridview,我是asp.net的新手。我在sqlserver中创建了一个包含3列的DB表图像ID、文件名和分数 文件名为C:\pics\beads.png或C:\pics\moreimages\scenary.jpeg 我使用C#asp.net创建了一个GridView。此Gridview应填充 (第1列)ImageID并从文件名(第2列)中获取图像,我创建了2个复选框列表,如下所示,它应该接受来自用户的图像的分数,并将其保存到DB表中 问题1 我可以填充图像ID,但图像没有填充 问题2. 我不知道如何访问

我是asp.net的新手。我在sqlserver中创建了一个包含3列的DB表<代码>图像ID、文件名和分数

文件名为
C:\pics\beads.png或C:\pics\moreimages\scenary.jpeg

我使用C#asp.net创建了一个GridView。此Gridview应填充

(第1列)ImageID并从文件名(第2列)中获取图像,我创建了2个复选框列表,如下所示,它应该接受来自用户的图像的分数,并将其保存到DB表中

问题1

我可以填充图像ID,但图像没有填充

问题2.

我不知道如何访问
复选框列表
,因为它位于模板中。选中的是默认的选择,即使我点击它也不会改变。应使用哪种方法/属性将所选内容保存到数据库。这是我的密码

<form id="form1" runat="server">
    <p style="height: 391px">
        <asp:GridView ID="GridView1" runat="server" Caption="Logos" Height="299px" Width="577px" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="ImageID" HeaderText="ImageID" />
                <asp:ImageField DataImageUrlField="FileName" ControlStyle-Width="100"
                    ControlStyle-Height="100" HeaderText="Image" AlternateText="No image">
                    <ControlStyle Height="100px" Width="100px"></ControlStyle>
                </asp:ImageField>
                <asp:TemplateField HeaderText="Score" AccessibleHeaderText="CheckBoxList" ValidateRequestMode="Enabled">
                    <ItemTemplate>
                        <asp:CheckBoxList runat="server" AutoPostBack="true" RepeatColumns="3" ID="test">
                            <asp:ListItem Selected="True" Value="5">Good</asp:ListItem>
                            <asp:ListItem Value="0">Not Good </asp:ListItem>
                            <asp:ListItem Value="3">OK</asp:ListItem>
                        </asp:CheckBoxList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>         

        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save" Width="130px" />
        <asp:Button ID="Button2" runat="server" OnClientClick="javaScript:window.close(); return false;" Text="Exit" Width="102px" />

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    </p>
</form>
谢谢你的时间
Rashmi

问题2: 要访问您的复选框,您可以使用

 GridViewRow row = GridView1.Rows[i];
 CheckBox Ckbox = (CheckBox)row.FindControl("test");
关于问题1

您可以像这样在Templatefield中使用ASP:Image,而不是ImageField

<asp:TemplateField HeaderText="Score" AccessibleHeaderText="CheckBoxList" ValidateRequestMode="Enabled">
   <ItemTemplate>
      <asp:Image ID="imageControl" runat="server" ImageUrl='<%# Eval("Filename") %>'></asp:Image>
   </ItemTemplate>
</asp:TemplateField>

您的代码有几个问题,下面是应该解决的问题:

如何修复图像(问题1)

正如@Guilherme在评论中所说,对于图像,使用URL而不是磁盘路径。 将图像磁盘路径
C:\pics\beads.png
C:\pics\moreimages\scenary.jpeg
替换为类似于
images/beads.png
images/scenary.jpeg

要使其正常工作,您需要有一个名为
Images
的文件夹,其中包含与
.aspx
文件位于同一目录级别的这两个文件

调整ASPX文件中的GridView1声明

在GridView1声明中,您应该:

  • 将处理程序附加到
    OnRowDataBound
    事件。这将允许您将
    Score
    数据集列正确绑定到
    Score
    gridview列
  • 将网格上的
    DataKeyNames
    属性设置为图像表的主键(在本例中为
    DataKeyNames=“ImageID”
  • 使用
    RadioButtonList
    而不是
    复选框列表
    ,因为根据数据集,您只能设置一个值,这就是
    RadioButtonList
    的作用。当需要多选时,通常使用
    复选框列表
  • 将处理程序附加到
    RadioButtonList
    上的
    SelectedIndexChanged
    事件。这将允许您将新值保存到数据库(问题2)
  • 以下是GridView声明的外观:

    <asp:GridView ID="GridView1" runat="server" Caption="Logos" Height="299px" Width="577px" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="ImageID">
            <Columns>
                <asp:BoundField DataField="ImageID" HeaderText="ImageID" />
                <asp:ImageField DataImageUrlField="FileName" ControlStyle-Width="100"
                    ControlStyle-Height="100" HeaderText="Image" AlternateText="No image">
                    <ControlStyle Height="100px" Width="100px"></ControlStyle>
                </asp:ImageField>
                <asp:TemplateField HeaderText="Score" AccessibleHeaderText="RadioButtonList" ValidateRequestMode="Enabled">
                    <ItemTemplate>                        
                        <asp:RadioButtonList runat="server" AutoPostBack="true" RepeatColumns="3" ID="test" OnSelectedIndexChanged="test_SelectedIndexChanged">
                            <asp:ListItem Value="5">Good</asp:ListItem>
                            <asp:ListItem Value="0">Not Good </asp:ListItem>
                            <asp:ListItem Value="3">OK</asp:ListItem>
                        </asp:RadioButtonList>
    
                        <!-- UPDATED! - keep the old values in a hidden field -->
                        <asp:HiddenField runat="server" ID="hfOldScore" Value='<%# Eval("Score") %>' />                    
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>         
    
    更新

    • GridView1
      的声明现在包含一个包含分数值的隐藏字段。您可以使用此隐藏字段来确定哪一行已更改,因此只能对更改的行触发保存
    • 现在,单击Save按钮即可完成保存,方法是在网格中的行中迭代,生成一个
      字典
      ,以仅保留更改
    • SaveToDB
      方法应该可以工作,但我自己无法测试

    文件名的值中应该有一个URL,如。在web上,类似C:\pics\beads.png的内容将不会呈现。谢谢!!我使用了Vignesh Kumar(问题1)和Lucian的代码(问题2)来让它工作。不过这里有一个陷阱。图像显示在IE中,但不显示在Chrome中。我不明白为什么。我不能向上投票,因为我是新会员。谢谢@Lucian的帮助。我试图保存到数据库只有在单击“保存”按钮。我是否需要在数组中保存值,然后保存它。是否有其他方法比此更好。根据需要保存的行数,您可以按顺序一次保存一个图像或批量保存项目。第一个非常简单:遍历gridview的行,获得ImageID和分数值,然后独立保存每一行。第二种方法更为复杂:您必须在一个DataSet对象中收集所有网格数据,然后使用SQL存储过程在批更新中保存整个数据。除非您确实确定要保存大量数据,否则我建议您使用第一个版本。#1选项,我们不能这样做。在SelectedIndexchanged中,我有Datacolumn d1=新Datacolumn(“ImageID”);dt.列。添加(d1);dt.Rows.Add(d1)…对其他列执行此操作。在保存按钮中,在声明连接对象后单击->adap.UpdateCommand=newsqlcommand(“更新ImagesTest set Score=@Score,DateNow=@DateNow,其中ImageID=@ImageID”,con);adap.Fill(dt);adap.更新(dt);con.Close();我收到空指针异常。我已根据您的评论更新了我的解决方案。我没有理解你在SelectedIndexChanged上的意思(顺便说一句,这不再需要了,因为保存是通过Save按钮进行的)。哇!!我在这里有一个敏锐的学习曲线。谢谢你抽出时间来,卢西恩
        For Each gvr As GridViewRow In Gridview1.Rows
            If (CType(gvr.FindControl("CheckBox1"), CheckBox)).Checked = True Then
                ReDim uPrimaryid(iCount)
                uPrimaryid(iCount) = New Integer
                uPrimaryid(iCount) = gvr.Cells("uPrimaryID").Text
                iCount += 1
            End If
        Next
    
    <asp:GridView ID="GridView1" runat="server" Caption="Logos" Height="299px" Width="577px" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="ImageID">
            <Columns>
                <asp:BoundField DataField="ImageID" HeaderText="ImageID" />
                <asp:ImageField DataImageUrlField="FileName" ControlStyle-Width="100"
                    ControlStyle-Height="100" HeaderText="Image" AlternateText="No image">
                    <ControlStyle Height="100px" Width="100px"></ControlStyle>
                </asp:ImageField>
                <asp:TemplateField HeaderText="Score" AccessibleHeaderText="RadioButtonList" ValidateRequestMode="Enabled">
                    <ItemTemplate>                        
                        <asp:RadioButtonList runat="server" AutoPostBack="true" RepeatColumns="3" ID="test" OnSelectedIndexChanged="test_SelectedIndexChanged">
                            <asp:ListItem Value="5">Good</asp:ListItem>
                            <asp:ListItem Value="0">Not Good </asp:ListItem>
                            <asp:ListItem Value="3">OK</asp:ListItem>
                        </asp:RadioButtonList>
    
                        <!-- UPDATED! - keep the old values in a hidden field -->
                        <asp:HiddenField runat="server" ID="hfOldScore" Value='<%# Eval("Score") %>' />                    
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>         
    
    protected void Page_Load(object sender, EventArgs e)        
        {
            //bind only the first time the page loads
            if (!IsPostBack)
            {                
                DataSet ds = GetData(sqlSel);
    
                if (ds.Tables.Count > 0)
                {
                    GridView1.DataSource = ds;
                    GridView1.DataBind();
                }
                else
                {
                    Response.Write("Unable to connect to the database.");
                }
            }
        }
    
        private DataSet GetData(string cmdSel)
        {
            //normally you should query the data from the DB
            //I've manually constructed a DataSet for simplification purposes
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("ImageID", typeof(int)));
            dt.Columns.Add(new DataColumn("FileName", typeof(string)));
            dt.Columns.Add(new DataColumn("Score", typeof(int)));
    
            dt.Rows.Add(100, @"Images/beads.png", 0);
            dt.Rows.Add(200, @"Images/moreimages/scenary.jpeg", 3);
            dt.Rows.Add(300, @"Images/moreimages/scenary.jpeg", 5);
    
    
            ds.Tables.Add(dt);
    
            return ds;
        }
    
        protected void Button1_Click(object sender, EventArgs e)
        {
            //UPDATED - iterate through all the data rows and build a dictionary of items
            //to be saved
            Dictionary<int, int> dataToUpdate = new Dictionary<int, int>();
            foreach (GridViewRow row in GridView1.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    int imageID = (int)GridView1.DataKeys[row.RowIndex].Value;
                    int oldScore;
                    int newScore; 
    
                    int.TryParse((row.FindControl("hfOldScore") as HiddenField).Value, out oldScore);
                    int.TryParse((row.FindControl("test") as RadioButtonList).SelectedValue, out newScore);
    
                    if (oldScore != newScore)
                    {
                        dataToUpdate.Add(imageID, newScore);
                    }
                }
            }
    
            //update only the images that were changed
            foreach (var keyValuePair in dataToUpdate)
            {
                SaveToDB(keyValuePair.Key, keyValuePair.Value);
            }
        }
    
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //we are only interested in the data Rows
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRow dataRow = (e.Row.DataItem as DataRowView).Row;
                //manually bind the Score column to the RadioButtonlist
                int? scoreId = dataRow["Score"] == DBNull.Value ? (int?)null : (int)dataRow["Score"];
                if (scoreId.HasValue)
                {
                    RadioButtonList test = e.Row.FindControl("test") as RadioButtonList;
                    test.ClearSelection();                    
                    test.SelectedValue = scoreId.Value.ToString();
                }
            }
        }
    
        protected void test_SelectedIndexChanged(object sender, EventArgs e)
        {
            RadioButtonList test = sender as RadioButtonList;
            GridViewRow gridRow = test.NamingContainer as GridViewRow;
    
            //obtain the current image Id
            int imageId = (int)GridView1.DataKeys[gridRow.RowIndex].Value;
    
            //obtain the current selection (we will take the first selected checkbox
            int selectedValue = int.Parse(test.SelectedValue);
    
            //UPDATED! - saves are now handled on the Save button click
            //SaveToDB(imageId, selectedValue);
    
        }
    
        private void SaveToDB(int imageId, int score)
        {
            //UPDATED!
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
            {
                connection.Open();
                using (SqlCommand command = connection.CreateCommand())
                {
                    command.Parameters.Add("@ImageID", imageId);
                    command.Parameters.Add("@Score", score);
                    command.CommandText = @"update [db1].[ImagesTest] set Score = @Score where [ImageID] = @ImageID";
                    command.ExecuteNonQuery();
                }
            }
    
        }