Showing posts with label Grid View. Show all posts
Showing posts with label Grid View. Show all posts

Monday, 4 February 2013

Selection In GridView With CheckBoxes


CheckBoxes Wise Selection In GridView in just 3 steps







1)In ASPX side
 your grid view must contain DataKeyNames
 and checkbox under templatefield

 <asp:GridView ID="GridViewtemp" runat="server"   DataKeyNames="Person_Id">



2)Now you have above grid where so many rows are avail and each row has a checkbox in it(as we placed a checkbox in templatefield's item template)

now when user click on these checkboxes and make out his selection we will provide him further a button 'btnselect' which will again bind a grid and show you only those selected row which were checked previously.

3)So On that btnselect_click event




In C# On Button Click

 protected void btnselect_Click(object sender, EventArgs e)
     {
       

    
             for (int i = 0; i < GridViewtemp.Rows.Count; i++)
             {
                 if (((CheckBox)GridViewtemp.Rows[i].FindControl("chkSONo")).Checked == true)
                 {
                     soid = ((Label)GridViewtemp.Rows[i].FindControl("
lblPersonid")).Text;


                     if (value == "")
                     {
                         value = soid;
                     }
                     else
                     {
                         value = value + "," + soid;
                     }


                 }

             }
             BindItemGrid(soid);
            
       
     }
     public void BindItemGrid(string Key)
     {
         query = " select * from tb_Stamping  where   [Person_Id] in (" + value + ")";
         SqlDataAdapter adp = new SqlDataAdapter(query, con);
         DataSet ds = new DataSet();
         adp.Fill(ds);
         gvselectcontent.DataSource = ds;
         gvselectcontent.DataBind();

     }

Monday, 17 September 2012

Bind DropDown Under GridView

Bind DropDown Under GridView
lets go from basic...



How to bind dropdown?

Normaly We Bind A Drop Downdown In Asp.net Page Like below....
.aspx

<asp:DropDownList ID="DropDownListGroup" runat="server"
DataTextField="GroupNm" DataValueField="GroupID" Height="18px"
style="margin-bottom: 0px" Width="205px">
</asp:DropDownList>

.cs
        SqlDataAdapter adp2 = new SqlDataAdapter("select * from Group", con);
        DataSet ds2 = new DataSet();
        adp2.Fill(ds2);
        DropDownListGroup.DataSource = ds2;
        DropDownListGroup.DataBind();      
        DropDownListGroup.Items.Insert(0, "---Select---");




but in case of Grid View Thing are bit different..
You need to workout in RowDataBound Click Event

1.Bind DropDown Under GridView In Item Template

 if (e.Row.RowType == DataControlRowType.DataRow)
     {

              DropDownList drdList = (DropDownList)e.Row.FindControl("DropDownListGroup");
             SqlDataAdapter adp = new SqlDataAdapter("select * from MST_Group", con);
             DataSet ds = new DataSet();
             adp.Fill(ds);
             drdList.DataSource = ds;
             drdList.DataBind();
             drdList.Items.Insert(0, "---Select---");

             }



2.Bind DropDown Under GridView In EditItem Template

 if (e.Row.RowType == DataControlRowType.DataRow)
     {
        
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
         {

             DropDownList drdList = (DropDownList)e.Row.FindControl("DropDownListGroup");
             SqlDataAdapter adp = new SqlDataAdapter("select * from MST_Group",con);
             DataSet ds = new DataSet();
             adp.Fill(ds);
             drdList.DataSource = ds;
             drdList.DataBind();
             drdList.Items.Insert(0, "---Select---");
         }
     }




3.Bind DropDown Under GridView In Footer Template

  if (e.Row.RowType == DataControlRowType.Footer)
     {

       ((Label)e.Row.FindControl("lblQty")).Text = totqty.ToString();
       TxtTotal.Text = totqty.ToString();
     
     }

Wednesday, 9 May 2012

Create Datatable,Insert/Delete Row In Data Table With Grid View

Create Datatable,Insert/Delete Row In Datatable and Finaly Save Record In SQL Server Table
Here we'll discuss about how to create Datatable(by creating coloumns and then filling rows),how to delete row from temporary created Datatable,and Finally how to fetch Datatabledata into a SQL Server table


Now Lets figure out what we need to do
1)Instantiate DataTable 
2)Create Colomns
3)Insert  Rows
4)Insert Rows with Previous saved Rows
5)Delete Rows
6)Finally save all Rows in SQL table



Now Lets discuss these points bit broadly
1)As we discussed above, here we are instantiating DataTable

                                               DataTable TempDTable=new DataTable();

2)Now creating/add columns in DataTable

                                          TempDTable.Columns.Add("ColumnName", typeof(string));


3)Insert Rows

                            DataRow row=new  TempDTable.NewRow();//Instantiating DataRow for inserting row  in particular columns

  
                               row["ColumnName"] = TextBox1.Text;
4)Insert Rows with Previous saved Rows

        if (ViewState["PagedataTable"] == null) //if there is any row in datatable
        {           
            //Add coloum for your DataTable
        }
        else(else if exist then just fill up rows)
        {
            TempDTable = (DataTable)ViewState["PagedataTable"];//store previous rows saved in viewstate to Datatable
        }
        DataRow row =new  TempDTable.NewRow();//Instantiating DataRow for inserting row in particular columns
     row["ColumnName"] =TextBox1.Text;//fill row for perticular column
       


                  if (ViewState["PagedataTable"] == null) //if there is any row in datatable (if not then create if exist then just fill up rows)
        {           
            //below code will create coloum for your DataTable
            TempDTable.Columns.Add("Type", typeof(string));
            TempDTable.Columns.Add("Group", typeof(string));
            TempDTable.Columns.Add("Name", typeof(string));
            TempDTable.Columns.Add("GroupID", typeof(string));
            TempDTable.Columns.Add("NameID", typeof(string));
            TempDTable.Columns.Add("Particular", typeof(string));
            TempDTable.Columns.Add("ChequeNo", typeof(string));
            TempDTable.Columns.Add("Credit", typeof(float));
            TempDTable.Columns.Add("Debit", typeof(float));
          
        }
        else
        {
            TempDTable = (DataTable)ViewState["PagedataTable"];
        }
        DataRow row;//Instantiating DataRow for inserting row in particular columns

        row = TempDTable.NewRow();

        row["Type"] = LabelType.Text;
        row["Group"] = DropDownListGroup.SelectedItem.Text;
        row["Name"] = DropDownListName.SelectedItem.Text;
        row["GroupID"] = DropDownListGroup.SelectedValue;
        row["NameID"] = DropDownListName.SelectedValue;
        row["Particular"] = TextBoxPerticular.Text;
        row["ChequeNo"] = TextBoxChequeNo.Text;
        row["Credit"] = TextBoxCredit.Text;
        row["Debit"] = TextBoxDebit.Text;


        TempDTable.Rows.Add(row);//Fetching All Row in DataTable
        ViewState["PagedataTable"] = TempDTable;//After filling rows,we are storing DataTable in  View State so that we insert new value with  previous stored value in viewstate
        this.GridView1.Visible = true;

        GridView2.DataSource = TempDTable;//Bind it with a grid view where you want to store datatable  values
        GridView2.DataBind();
        ButtonSaveRecord.Visible = true;

5)To Check whether a coloumn entry alreay Existed with your Entered Value

 if (ViewState["tempProductDatatable"] != null)
        {
            TempDTable= (DataTable)ViewState["PagedataTable"];
            for (int i = 0; i < TempDTable.Rows.Count; i++)
            {
                if (TextBoxITEMCODE.Text == TempDTable.Rows[i]["Item_Code"].ToString())
                {
                    LblCode.Text = "xx";
                }
            }
        }
        if (LblCode.Text == "xx")
        {
                // means value already existed in Item_Code coloumn
          }
        else
        {
                // means value does not existed in Item_Code coloumn
         }







6) Delete Rows
between creating and fetching record from datatable to SQL server table you may also like (you must know) how to delete a record/row if its needs to be deleted!!

So here is a below code which will fired on RowDeleting Command of grid view!!


 protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int s = e.RowIndex;
        DataTable TempDtForDel = (DataTable)ViewState["PagedataTable"];
        TempDtForDel.Rows[s].Delete();
        GridView2.DataSource = TempDtForDel;
        GridView2.DataBind();
    }
So we have Done!!we've created a datatable which will further fillup rows as per button click event

7) Finally save all Rows in SQL table:
Now thing comes later is save that data (in datatable in SQL Server table) so here we go...
a)Here we are first creating a table to save final value from data table...

CREATE TABLE [dbo].[tb_Sample]
(
    [Voucher_Id] [int] IDENTITY(1,1) NOT NULL,
    [VoucherType] [varchar](50) NULL,
    [OfGroup] [varchar](100) NULL,
    [Acc_Name] [varchar](100) NULL,
    [Particulars] [varchar](100) NULL,
    [ChequeNo] [varchar](60) NULL,
    [Debit] [float] NULL,
    [Credit] [float] NULL
)

b)Now below is a command to save datatable records/rows in SQL server table

        con.Open();
        DataTable dtTemp = new DataTable();
        dtTemp = (DataTable)ViewState["PagedataTable"];

        for (int i = 0; i < dtTemp.Rows.Count; i++)
        {
            SqlCommand cmd2 = new SqlCommand("insert into tb_Sample values (@VoucherType,@Group,@Acc_Name, @Particulars,@ChequeNo,@Debit,@Credit)", con);


            cmd2.Parameters.Add("@VoucherType", SqlDbType.VarChar).Value = dtTemp.Rows[i]["Type"].ToString();
            cmd2.Parameters.Add("@Group", SqlDbType.VarChar).Value = dtTemp.Rows[i]["GroupID"].ToString();
            cmd2.Parameters.Add("@Acc_Name", SqlDbType.VarChar).Value = dtTemp.Rows[i]["NameID"].ToString();
            cmd2.Parameters.Add("@Particulars", SqlDbType.VarChar).Value = dtTemp.Rows[i]["Particular"].ToString();
            cmd2.Parameters.Add("@ChequeNo", SqlDbType.VarChar).Value = dtTemp.Rows[i]["ChequeNo"].ToString();
            cmd2.Parameters.Add("@Debit", SqlDbType.VarChar).Value = dtTemp.Rows[i]["Debit"].ToString();
            cmd2.Parameters.Add("@Credit", SqlDbType.VarChar).Value = dtTemp.Rows[i]["Credit"].ToString();
            cmd2.ExecuteNonQuery();
        }
        con.Close();
        GridfinalBind();//binding gridview


//below is nothing but a way of inserting datatable record into server table but i m already using above method so u dont have to worry about below code....its all commented!!
        //foreach (DataRow row in TempDTable.Rows)
        //{
        //    SqlDataAdapter sqlInsert = new SqlDataAdapter();
        //    sqlInsert.InsertCommand = con.CreateCommand();
        //    sqlInsert.InsertCommand.CommandText = "INSERT INTO ACE_SALE_CONTRACT_UPDATE (ITEM_ID, ITEM_NO) SELECT '" +
        //    (row["ITEM_ID"]) + "' AS ITEM_ID, '" +
        //    (row["ITEM_NO"]) + "' AS ITEM_NO";
        //    sqlInsert.InsertCommand.ExecuteNonQuery();
        //}


and here is the final running sample...kindly attach your own webconfig and run it!

Thursday, 3 May 2012

Print Out Only Grid View Or Any Fix Content Area In Asp.net Page

Print out only Grid view,Datalist,Detail view or Any fixed content area like <div> in asp.net page

Some time you have so many things in your single page lets say a GRIDVIEW,a DATALIST,a DIV ,or any other(server control which has a ID)from which you want to print the individual content and not the whole page. From this i mean how to print a fix content area from whole page in asp.net,lets see how easly it could be done.



Just take a look at below webpage .
Now as a developer how could you  print out only red marked areas with a print button click.








In case you need help lets proceed with this tutorial...

Lets take brief look at simple screen below

 






Its simply include
a div with id name printable and runat="server"
then my text under that div
and some text outside that div


 Here div is server control  as i made it by giving it a id name and runat="server" as below

<div runat="server" id="printable">
          
 </div>




Similarly it could be any control either Datalist,Gridview or any Control
Now in final there is image button...(you don't have to fire its click event!)


Just write this code in Page_Load 
and at the time you click it ,Our page will automatically recognize it and give you the print out option!


 protected void Page_Load(object sender, EventArgs e)
    {
            string printScript =@"function PrintGridView()
         {
            var gridInsideDiv = document.getElementById('printable');
            var printWindow = window.open('gridview.htm','PrintWindow','letf=0,top=0,width=850,height=300,toolbar=1,scrollbars=1,status=1');
            printWindow.document.write(gridInsideDiv.innerHTML);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();}";
            this.ClientScript.RegisterStartupScript(Page.GetType(), "PrintGridView", printScript.ToString(), true);
            btnPrint.Attributes.Add("onclick", "PrintGridView();"); 
   }


and finaly the sample code is here...



Print Only Grid View in ASP.net

ASP.net How to Print Only GridView < div id ="gridviewDiv" >   < asp:GridView ID ="gridViewToPri...