当尝试添加复选框到网格视图上的asp.net表单我得到错误?

k5ifujac  于 2023-02-01  发布在  .NET
关注(0)|答案(2)|浏览(121)

我用C#处理www.example.com Web表单我需要在gridview上添加复选框列作为最后一列asp.net web forms with c# I need to add checkbox column as last column on gridview
但我不知道怎么加

static  string con =
   "Data Source=DESKTOP-L558MLK\\AHMEDSALAHSQL;" +
   "Initial Catalog=UnionCoop;" +
   "User id=sa;" +
   "Password=321;";
        SqlConnection conn = new SqlConnection(con);
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GridViewSearch.DataSource = GetDataForSearch();
                GridViewSearch.DataBind();
            }

        }

        public DataTable GetDataForSearch()
        {
            string response = string.Empty;
            SqlCommand cmd = new SqlCommand();
            DataTable dt = new DataTable();
            try
            {
                conn.Open();
                cmd.Connection = conn;
                cmd.CommandText = "select top 10 datelogged AS EntredDatetime, Doc_type AS OrderType, Printer_name, BranchID AS BranchCode, id from Print_Report";
                cmd.CommandType = CommandType.Text;
                cmd.CommandTimeout = 50000;
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                sda.Fill(dt);
            }
            catch (Exception ex)
            {
                response = ex.Message;
            }
            finally
            {
                cmd.Dispose();
                conn.Close();
            }
            return dt;

        }

on aspx page
 <asp:GridView ID="GridViewSearch" runat="server">
        </asp:GridView>
GridViewSearch.DataSource = GetDataForSearch();
                DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
                checkColumn.Name = "X";
                checkColumn.HeaderText = "X";
                checkColumn.Width = 50;
                checkColumn.ReadOnly = false;
                checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
                GridViewSearch.Columns.Add(checkColumn);
                GridViewSearch.DataBind();

我在下面的行中得到错误

GridViewSearch.Columns.Add(checkColumn);

参数1无法从系统.窗口.窗体.数据网格视图复选框转换为系统. web.用户界面. web控件.数据绑定字段
那么这个问题怎么解决呢?

iszxjhcz

iszxjhcz1#

在我看来,如果你想说一个按钮,或复选框,或下拉菜单?
为什么不把它添加到标记中呢。
所以,这样说:

<div id="MyGridPick" runat="server" style="display:normal;width:40%">
    <asp:Label ID="lblSel" runat="server" Text="" Font-Size="X-Large"></asp:Label>
    <br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="ID"  cssclass="table table-hover" OnRowDataBound="GridView1_RowDataBound" >
        <Columns>
            <asp:BoundField DataField="FirstName" HeaderText="FirstName"     />
            <asp:BoundField DataField="LastName" HeaderText="LastName"       />
            <asp:BoundField DataField="City" HeaderText="City"                />
            <asp:BoundField DataField="HotelName" HeaderText="HotelName" ItemStyle-Width="120px"     />
            <asp:BoundField DataField="Description" HeaderText="Description" />
            <asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
                <ItemTemplate>
                    <asp:CheckBox ID="chkSel" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

那么我要加载的代码是这样的:

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

    void LoadGrid()
    {
        SqlCommand cmdSQL = 
            new SqlCommand("SELECT * FROM tblHotelsA ORDER BY HotelName");
        GridView1.DataSource = MyRstP(cmdSQL);
        GridView1.DataBind();
    }

当然,我已经厌倦了一遍又一遍地输入连接字符串,所以,我有一个"genreal"例程,如下所示:

public DataTable MyRstP(SqlCommand cmdSQL)
    {
        DataTable rstData = new DataTable();
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            cmdSQL.Connection = conn;
            using (cmdSQL)
            {
                conn.Open();
                rstData.Load(cmdSQL.ExecuteReader());
            }
        }
        return rstData;
    }

运行以上结果:

所以,当你可以直接把一个复选框放到网格视图中时,很难"添加"一个复选框控件。
按钮也是如此,也许我们需要一个按钮来"查看"或编辑上面的行,或者类似的东西。
所以,再一次,放一个简·巴顿,像这样说:

<asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center" >
                <ItemTemplate>
                    <asp:Button ID="bView" runat="server" Text="View" CssClass="btn"
                        OnClick="bView_Click" />
                </ItemTemplate>
            </asp:TemplateField>

现在我们有了这个

甚至更好?
既然那个按钮(或复选框)是一个普通的jane标准控件?
然后你可以添加标准事件,比如点击事件,或者任何你想要的。
说出这段代码来点击按钮(显示如何获取当前行)。

protected void bView_Click(object sender, EventArgs e)
{
    Button btn = sender as Button;
    GridViewRow gRow = btn.NamingContainer as GridViewRow;
    int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];

    SqlCommand cmdSQL = 
        new SqlCommand("SELECT * FROM tblHotelsA WHERE ID = @ID");
    cmdSQL.Parameters.Add("@ID", SqlDbType.Int).Value = PKID;

    DataTable dtHotel = MyRstP(cmdSQL);
    General.FLoader(MyEditArea, dtHotel.Rows[0]);

    MyGridPick.Style.Add("display", "none");        // hide grid
    MyEditArea.Style.Add("display", "normal");      // show edit div area

}

现在我们看到了:

编辑:处理每个选中/选定的行。

这个:

protected void cmdSelProcess_Click(object sender, EventArgs e)
{
    // process all rows in GV with check box

    String sPK = "";
    List<int> MySelected = new List<int>();
    foreach (GridViewRow gRow in GridView1.Rows)
    {
        CheckBox chkSel = (CheckBox)gRow.FindControl("chkSel");
        if (chkSel.Checked)
        {
            int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
            // add pk value of row to our list
            MySelected.Add(PK);
            // Or we could process data based on current gRow
            if (sPK != "")
                sPK += ",";

            sPK += PK.ToString();
            Debug.Print(PK.ToString());
        }

    }
    // at this point, we have a nice list of selected in MySelected
    // or, maybe process as a data table

    SqlCommand cmdSQL =
        new SqlCommand($"SELECT * FROM tblHotelsA where ID IN({sPK})");

    DataTable rstSelected = MyRstP(cmdSQL);
    // 
    foreach (DataRow dr in rstSelected.Rows)
    {
        // do whatever
    }

}
busg9geu

busg9geu2#

Datagridviewcheckboxcolumn是Windows formx对象。您正在使用Web窗体。有关webforms check box field的信息,请参阅下面的链接

CheckBoxField checkColumn = new CheckBoxField();

相关问题