DotNet Friends

May 28, 2008

May 21, 2008

scrollable gridview in asp.net

image

Steps:

1) Create Simple Web Application Using Asp.net (with C#).

2) put the below control on the form. or copy the below code and paste in to application.

Control Id Set Style Of Control
GridView GridView1
Panel other
style="width:100px;" 
Panel pnlGrid
style="overflow:auto;height:200px;width:100px;"
<asp:Panel ID="other" runat="server" style="width:100px;" >
</asp:Panel>
<asp:Panel ID="pnlGrid" runat="server" style="overflow:auto;height:200px;width:100px;" >
  <asp:GridView ID="GridView1" runat="server" >
  </asp:GridView>
</asp:Panel>

3) on the cs file Put the below code.

protected void Page_Load(object sender, EventArgs e)
    {
      //check the page postback
      if (!IsPostBack)
      {
        GridView1.Attributes.Add("style", "table-layout:fixed");
        //here i am use list instead of database
        System.Collections.Generic.List<string> objDataDs = new System.Collections.Generic.List<string>();

        for (int i = 0; i < 100; i++)
        {
          objDataDs.Add(i.ToString());
        }

        GridView1.DataSource = objDataDs;
        GridView1.DataBind();
      }
    }

4) now in the javascript put below code.

 <script language="javascript" type="text/javascript">
function ChangeTheHeaderStyle()
{
//get the clientid of the GridView Where you want to fixed column
var tbl = document.getElementById('<%= GridView1.ClientID%>');
//copy all the row from gridview1
var tblNoOfRow = tbl.cloneNode(true);
//remove all the row from tblNoOfRow
for(var i = tblNoOfRow.rows.length -1;i > 0;i--)
    tblNoOfRow.deleteRow(i);

////delete row 0 (means header from the original)
tbl.deleteRow(0);
////append the remaining row from the tblNoOfRow
other.appendChild(tblNoOfRow);
}
//call the function
window.onload = ChangeTheHeaderStyle

</script>
Check The Application.

Thanks


http://amitpatriwala.blogspot.com/

May 19, 2008

Difference Between Environment.CurrentDirectory And Application.ExecutablePath

here i am using simple windows application.

steps:

1) Create Simple Windows Application using VB.net 2.0.

2) put the button (id=button1) on the form.

3) On the Button Click Event put the below code.

Private Sub Button1_Click(ByVal sender As System.Object,
               ByVal e As System.EventArgs) Handles Button1.Click
'get the EnvironmentPath
 MsgBox(" EnvironmentPath " & Environment.CurrentDirectory.ToString())
'get the application path
 Dim str As String = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\"))
 MsgBox(" ApplicationPath " & str)
End Sub

4) output of this Application.

EnvironmentPath : Your Application Path + \bin\Debug

ApplicationPath : Your Application Path + \bin\Debug

here both are same.

5) Create a *Set Up Project and install the set up in to your computer.

EnvironmentPath : Your Drive + Documents and Settings\ + UserFolder

ApplicationPath : Your Drive + Documents and Settings + UserFolder + \Start Menu\Programs

the above path is different.

when you use any file or report path and at that time if you use the EnvironmentPath that will give error.

*Set Up Project :

create set up project using the dotnet i give hint ( Open File Menu : Create New Project

–> Select Other Project Types

–> Set Up And Deployment (select Setup Project).

thanks.

May 16, 2008

Create Template In DotNet

Microsoft Visual Studio Provided the inbuilt facility to create Template.I just Explain how to use that thing.

Steps:

1) Create Simple Web Application (Asp.net with C#). now Open the File Menu and Check Whether Export Template Exist there.if Export Template Option there then skip the step2.

image ( Figure 1)

2) if the Export Template Option Not there then how to add that option follow the below steps.

2.1) Open the Tool Menu and Select the Customize Option.

image

2.2) below screen is Open when you click on the Customize Option.select File From Category.

image

2.3) select the Export Template from File and Drag that in to the File Menu.

image

2.4) now Export Template Option Is Available in to File Menu.

image

3) click on the Export Template option in file Menu. below screen is available. now there is two option either you create Project Template or Item Template. in Project Template whole existing project is covered. when you select the Item Template you select page(aspx) from the existing (current) project.

image

4) here i am select project template and press Next button.after that the below screen is available. give the template icon and template name. and press the finish button newly created template location is open close it.

image

5) now close this project and new Website at time you see the added project template there.select that template new project is created.

image

6) how to add Item Template. same as above select the Export Template Option From the File Menu. and select the Item Template and press Next Button.

image

7) select the page from the list of pages. here i have only one page.press the Next button.

image

8 ) select the item references from below screen and press the next button.

image

9) enter the template icon and name. press the finish button newly created item template path is open close it.close the project and open a new project.

image

10) select Web Site Menu and choose option Add New Item. the below screen is open. choose the item template and Add In to project.

image

Thnx

Insert Null Value in DateTime Column SqlServer 2005 using asp.net

steps:

1) Create Simple web application (asp.net with C#).

2) create below table in the database. here i made table (table_1 in test database).

DataBase Name :Test
Table Name : Table_1
ColumnName       ColumnDataType
id               int (Auto Increment & Primary Key)
code             varchar(50) (Allow Null True)
date             datetime (Allow Null True)
 3) put the below control on the form.

3.1) Calendar (id –> Calendar1)

3.2) Button (id –> btnInsert)

3.3) Button (id –> btnGet)

3.4) Label (id –> lblDataValue)

4) put the below code in to C# page.

Add below name space first :

using System.Data.SqlClient;
copy the below code and check.
 //connection string
    //please change as per your server and database 
    string constr = @"Data Source=(local);Initial Catalog=test;Integrated Security=True";
    public int insertedId
    {
        get { return Convert.ToInt32(ViewState["inserttedid"]); }
        set { ViewState["inserttedid"] = value; }
    }
    protected void btnInsert_Click(object sender, EventArgs e)
    {
        //if user is not selected any value from calendar at that time null is inserted
        //otherwise selected date is inserted
        string datetime = Calendar1.SelectedDate.Date.Equals(DateTime.MinValue) == true ? "Null" : "'" + Calendar1.SelectedDate + "'";
        string strins = "insert into table_1 values " +
            "('amit'," + datetime + ");select scope_identity();";
        SqlConnection sqlcon = new SqlConnection(constr);
        SqlCommand cmd = new SqlCommand(strins, sqlcon);
        sqlcon.Open();
        //get the id of inserted row using Scope_Identity function
         insertedId = Convert.ToInt32(cmd.ExecuteScalar());
        sqlcon.Close();
    }
    protected void btnGet_Click(object sender, EventArgs e)
    {
        //get the inserted record
        string strSelect = "Select * from table_1 where id =" + insertedId;
        SqlConnection sqlcon = new SqlConnection(constr);
        SqlCommand cmd = new SqlCommand(strSelect, sqlcon);
        sqlcon.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            //set the value in the label for display purpose  
            lblDataValue.Text = dr["date"] == System.DBNull.Value ? DateTime.MinValue.ToShortDateString() : Convert.ToString(dr["date"]);
        }
        sqlcon.Close();
    }

Thanks.


http://amitpatriwala.blogspot.com/

May 15, 2008

Get Connection String from Windows Registry using C#.net

First of first how to open windows registry editor ?

Open Run Menu (Windows + R) and type regedit the below screen is open.

clip_image002

(Figure 1)

here I am created the simple application using windows C#.net 2.0.

image

steps:

1) Create Simple Windows Application using C#. add the namespace

using Microsoft.Win32;

2) put the below control on the form.

Control Control Id Control Value
label label1 Enter Connection String
label lblGetConnectionString
TextBox txtConnectionString
Button btnSaveConnectionStringInDB Save Connection String In Data
Button btnRetriveConnectionStringFromRegistry Retrive Connection String From Windows Registry

3) in the Figure 1 Local Machine Contain Five Key

1) Hardware 2) Sam 3) Security 4) Software 5) System.

in the figure 1 only one key is display. now we code and then new key is added under the

HKEY_LOCAL_MACHINE. in below screen the brief idea is given.

image

4) Now Put the Below code in to .CS File.

4.1) Declare the global variable

//configuration data for the local machine
   //Windows registry base key HKEY_LOCAL_MACHINE
   RegistryKey objRegistryKey = Registry.LocalMachine;
4.2) on the button click (btnSaveConnectionStringInDB) put below code.
private void btnSaveConnectionStringInDB_Click(object sender, EventArgs e)
   {
     try
     {
       //now set the new key under the base key
       //argument 1) Name Of The Key (MyConnectionString)
       //         2) Key (TextBox Enter Value)
       //         3) value type (string)
       //now i am use hardcoded key value
       objRegistryKey.SetValue("MyConnectionString", txtConnectionString.Text, RegistryValueKind.String);
       MessageBox.Show("Key Is Sucessfully Registered");
     }
     catch (Exception ex)
     {
       MessageBox.Show("Can Not Store Data In Registry" + ex.Message.ToString());
     }
   }

4.3) on the button click (btnRetriveConnectionStringFromRegistry) put below code.

private void btnRetriveConnectionStringFromRegistry_Click(object sender, EventArgs e)
{
  string values = (string)objRegistryKey.GetValue("MyConnectionString");
  //display the connection string value in the label
  lblGetConnectionString.Text = values;
}

5) Add Key In to Windows Registry.

image

After the get message open the windows registry.

image

entered key is added successfully please check the figure1 and last this figure.

6) Get the Value from the RegistryKey (MyConnectionString)

image

Thnx

May 10, 2008

CheckBox Column In GridView handled using Client-Site Script (Javascript)

GridViewImage

Purpose:

handled the check box check event without postback using javascript and save the id in the hidden field. in the above

“fig1″ user selected the check one by one. after the selection of all the check box the header is selected which is described

in the “fig2″. now user is changed the page index described in the “fig3″ and selected the page1 described in the “fig4″ here all

the check box is checked.

Steps:

1) Create the Simple Web Application.

2)put the below code in the .aspx file.

<asp:HiddenField  ID="TotalNoOfRecord" Value="," runat="server"/>
    <asp:HiddenField ID="SelectedRecord" Value ="," runat ="server" />
    <div>
        <asp:GridView AutoGenerateColumns="False" ID="GridView1" 
        runat="server" Style="z-index: 100; left: 326px; position: absolute;
            top: 148px" OnRowDataBound="GridView1_RowDataBound" 
            AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" 
            PageSize="5" CellPadding="4" ForeColor="#333333" GridLines="None">
            <Columns>
            <asp:TemplateField>
            <HeaderTemplate>
            <asp:CheckBox ID="chkHeader" runat="server" />
            </HeaderTemplate>
            <ItemTemplate>
            <asp:CheckBox ID="chkItemTemplate" runat="server" />
            </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Id" Visible="False">
            <ItemTemplate>
            <asp:Label ID="lblId" Text='<%# Eval("Id") %>' runat="server"></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText ="Code">
            <ItemTemplate>
            <asp:Label ID="lblCode" Text='<%# Eval("Code") %>' runat="server"></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#EFF3FB" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
    
    </div>

3) put the below Javascript in to code.

 <script language="Javascript" type="text/javascript">
    //fire when the header checkbox is click
    function SelectAll(chkid)
    {
    //get the form
     var objfrm = document.forms[0];
     //find the element length of the form
     for (i=0;i<objfrm.elements.length;i++)
     {
       //check the element type (it is check box) and it in the gridview1 
       if (objfrm.elements[i].type == "checkbox" && objfrm.elements[i].name.indexOf('<%= GridView1.ClientID %>') >= 0)
       {
           objfrm.elements[i].checked = document.getElementById(chkid).checked;
       }
     }
      //get the hidden field of the selected id
      var SelectedRecord = document.getElementById('SelectedRecord').value;
      //selectedid in the hidden field
      var hdnIds = SelectedRecord.split(",");
      //no of record on the page
      var hdnnoofrecord = document.getElementById('TotalNoOfRecord').value.split(",");
        
     if(document.getElementById(chkid).checked)
     {    
        //check the value in the SelectedRecord
        for(var i=1;i< hdnnoofrecord.length-1;i++)
        {    
            //if already exist at that time we not added that id into the 
            //SelectedRecord else Add
            if(SelectedRecord.indexOf(',' + hdnnoofrecord[i] +',')<0)
            {
                SelectedRecord += hdnnoofrecord[i] + ',';
            }
        }       
        document.getElementById('SelectedRecord').value =SelectedRecord;
     }
     else
     {
      //check the value in the SelectedRecord
        for(var i=1;i< hdnnoofrecord.length-1;i++)
        {
          //unselected row id is replace (example id 1 is unchecked --> ,1, replace with ,)  
          SelectedRecord = SelectedRecord.replace(',' + hdnnoofrecord[i] + ',',','); ;
        }        
         document.getElementById('SelectedRecord').value =SelectedRecord;
     }
     
    }
    
    //header checkbox check /uncheck function
    function HeaderCheckUnCheck()
    {
        var header =true;
        var chkheaderchkbox;
        var AllRecordSelect = true;
        var objfrm = document.forms[0];
         
        for (i=0;i<objfrm.elements.length;i++)
        {
          if (objfrm.elements[i].type == "checkbox" && objfrm.elements[i].name.indexOf('<%= GridView1.ClientID %>') >= 0)
          {
           if(header ==true)
           {
            chkheaderchkbox=objfrm.elements[i];
            header =false;
           } 
           else
           {
            if(objfrm.elements[i].checked ==false) 
            {
             AllRecordSelect =false;
            }
           }
          }
        }
        //all the row check box is checked then header check box is click
         if(AllRecordSelect ==true)
         {
             chkheaderchkbox.checked =true;
         }
         else 
         {
            chkheaderchkbox.checked =false;
         }
    }
    //individual check box click at that time fire
    function Select(chkid,selectedrowvalue)
    {    
        var SelectedIds =document.getElementById('SelectedRecord').value;
        if(document.getElementById(chkid).checked)
        {
            if(SelectedIds.indexOf(',' + selectedrowvalue + ',') <0)
                SelectedIds += selectedrowvalue + ',';
        }
        else
        {
            SelectedIds = SelectedIds.replace(',' + selectedrowvalue + ',',',');
        }   
        document.getElementById('SelectedRecord').value = SelectedIds;
        HeaderCheckUnCheck();
    }
    </script>

4) Here I Created one class instead of connection with database. here class is serialized because i save the data in the viewstate.

[Serializable]
public class MyData
{
  private int _Id;
 
  public int Id
  {
    get { return _Id; }
    set { _Id = value; }
  }
 
  private String _Code;
 
  public String Code
  {
    get { return _Code; }
    set { _Code = value; }
  }
 
  public MyData(int id, string code)
  {
    this.Id = id;
    this.Code = code;
  }
}

5) put the below code in the .CS File.

 public System.Collections.Generic.List<MyData> Data
  {
    get { if (ViewState["data"] ==null)
            return new System.Collections.Generic.List<MyData>( );
      return (System.Collections.Generic.List<MyData> ) ViewState["data"]; }
    set { ViewState["data"] = value; }
  }
    
 
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {
        System.Collections.Generic.List<MyData> obj = new System.Collections.Generic.List<MyData>();
         
        for (int i = 0; i < 10; i++)
        {
          obj.Add(new MyData(i,"a" + i.ToString()  ));
        }
 
        Data = obj;
        GridView1.DataSource = Data;
        GridView1.DataBind();
 
      }
 
      Response.Write(SelectedRecord.Value);
      //Response.Write(TotalNoOfRecord.Value);
    }
  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.Header)
    {
      CheckBox chk = ((CheckBox)e.Row.FindControl("chkHeader"));
      chk.Attributes.Add("onclick", "SelectAll('" + chk.ClientID + "');");
    }
    else if(e.Row.RowType ==DataControlRowType.DataRow)
    {
      CheckBox chk = ((CheckBox)e.Row.FindControl("chkItemTemplate"));
      Label lbl = ((Label)e.Row.FindControl("lblId"));
      chk.Attributes.Add("onclick","Select('" + chk.ClientID + "' ,'" + lbl.Text + "')");
 
      if (SelectedRecord.Value.Contains("," + lbl.Text + ","))
      {
        chk.Checked = true;
      }
 
      TotalNoOfRecord.Value += lbl.Text +",";
    }
   
  }
  protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
  {
    TotalNoOfRecord.Value = ",";
    GridView1.PageIndex = e.NewPageIndex;
    GridView1.DataSource = Data;
    GridView1.DataBind();
  }
Thnx 

May 8, 2008

Use Output clause in Delete Statement in sqlserver 2005

Here i give simple example of delete statement with output clause.

if you want track the deleted row information at that time generally

we preffered trigger right?

here we inserte the deleted row in the other history table. we create

the two talbe one is data table and other for history purpose.

1) Create Table (Name:Table_1)

GO

CREATE TABLE [dbo].[Table_1]

( [id] [int] IDENTITY(1,1) NOT NULL,

[varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,

CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY]

2) Create Table For Save Deleted Record in other table (DeletedTblInfo)

GO

CREATE TABLE [dbo].[DeletedTblInfo]

( [DeletedTableInfoId] [int] IDENTITY(1,1) NOT NULL,

[DeletedTableId] [int] NULL,

[DeletedRowId] [int] NULL,

 [DeletedDateTime] [datetime] NULL,

CONSTRAINT [PK_DeletedTblInfo] PRIMARY KEY CLUSTERED ( [DeletedTableInfoId] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY]

3) insert data into data table

go

INSERT INTO Table_1

 (code)

VALUES

(‘test1′)

 go

INSERT INTO Table_1

 (code)

 VALUES

(‘test2′)

go

INSERT INTO Table_1

(code)

VALUES

(‘test3′)

go

INSERT INTO Table_1

(code)

VALUES

(‘test4′)

4) now delete from table 1 where id =4

–here the record save in the DeletedTblInfo

–DeletedTableId : the table id where data is deleted or the table name if you want then.

–DeletedRowId : deleted RowId

–DeletedDateTime : deleted DateTime

DELETE FROM Table_1

OUTPUT 1,DELETED.ID,getdate()

INTO DeletedTblInfo WHERE (Id = 4);

–now see the result in the history table

DeletedTableInfoId DeletedTableId DeletedRowId DeletedDateTime
1 1 4 5/7/2008 12:53:52 PM

Blog at WordPress.com.