Home > Mobile >  when try to add check box to grid view on asp.net forms i get error?
when try to add check box to grid view on asp.net forms i get error?

Time:01-30

I work on asp.net web forms with c# I need to add checkbox column as last column on gridview

but i don't know how to add it

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();

I get error on line below

GridViewSearch.Columns.Add(checkColumn);

argument 1 can't convert from system.windows.forms.datagridviewcheckbox to system.web.ui.webcontrol.databoundfield

so how to solve this issue please ?

CodePudding user response:

Seems to me, that if you want say a button, or check box, or dropdown?

why not just add it to the markup.

So, say like this:

<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"  css 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>

Then my code to load is this:

    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();
    }

Now, of course I get VERY tired of typing that connection string stuff over and over. So, I have a "genreal" routine like this:

    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;
    }

And the result of running above:

enter image description here

So, kind of hard to make the case to "add" a check box control, when you can just drop one into the gridview.

Same goes for a button, maybe we want a button to "view" or edit the above row, or some such.

So, once again, just drop in a plain jane button, say like this:

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

And now we have this:

enter image description here

And EVEN better?

Well, since that button (or check box) is a plain jane standard control?

then you can add standard events, like a click event, or whatever you want.

Say this code for the button click (shows how to get current row).

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

}

And we now get/see this:

enter image description here

Edit: Process each checked/selected row.

this:

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
    }

}

CodePudding user response:

Datagridviewcheckboxcolumn is a Windows formx object. You are working in web forms. Please see the link below for information on the webforms check box field

    CheckBoxField checkColumn = new CheckBoxField();
  • Related