728x90


최근 Linq로 DB에서 조회해 온 값을 Json으로 변경하는 작업을 했다. 

예제의 경우 프로시져에서 조회한 값을 Json으로 변경.


Using 먼저 추가!!

using Newtonsoft.Json;


소스에서는 아래와 같이 사용하면 됨. 

var r = JsonConvert.SerializeObject((from p in ctx.프로시져(param1, param2) select p).ToList());

물론 프로시져 아니고 테이블이어도 코드는 동일합니다. 


관련하여 자세한 내용은

http://www.newtonsoft.com/json

해당 페이지에서 확인 하시면 됩니다. 


728x90
728x90

출처 사이트 URL: http://www.dotnetgallery.com/kb/resource18-Gridview-header-checkbox-select-and-deselect-all-rows-using-client-side-Jav.aspx.aspx

 

 

 

 

영어 설명 밑에 제 맘대로 한글로 해석 한 내용 입니다. 해석이 엉망이니 직접 해석하시는 편을 추천합니다.

 

Gridview header checkbox select and deselect all rows using client side JavaScript and server side C#

--> 자바스크립트 또는 서버단 소스를 사용하여 그리드뷰 헤더에 체크 박스 선택 또는 선택 해제

 

 

Introduction

--> 소개


Adding checkbox in gridview header template and select/deselect all rows is a common requirement in most of the asp.net projects and frequently asked questions also. Here I will explain how to add checkbox in header template of gridview and select/deselect all rows using client side javascript and server side code.

--> 체크박스를 그리드 뷰 헤더 템플릿에 추가하고 선택/선택해제는 대부분의 asp.net 프로젝트에서 공통적으로 요구 되는 사항이고 자주 Q&A 된다. 여기서 내가 설명할 것은 GridView Hearder Template에 체크박스를 추가하는 방법과 클라이언트 사이드 자바스크립트와 서버 사이드 코드를 사용하여 전체선택/선택해제 하는 방법이다.

 

 

Add Checkbox in Gridview header template

--> 그리드뷰 헤더 템플리에 체크 박스 추가


Create the asp.net project and drag the gridview control then format as likes below.

--> asp.net 프로젝트를 만들고 그리드뷰 컨트롤을 드래그.(복사하라는건가??) 아래 포맷 처럼 만들어라. 

<asp:GridView ID="GridVwHeaderChckbox" runat="server" AutoGenerateColumns="False"
Font-Names="Verdana" PageSize="5" Width="55%" BorderColor="#CCCCCC" BorderStyle="Solid"
BorderWidth="1px">
<AlternatingRowStyle BackColor="#BFE4FF" />
<PagerStyle BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
<HeaderStyle Height="30px" BackColor="#6DC2FF" Font-Size="15px" BorderColor="#CCCCCC"
BorderStyle="Solid" BorderWidth="1px" />
<RowStyle Height="20px" Font-Size="13px" BorderColor="#CCCCCC" BorderStyle="Solid"
BorderWidth="1px" />
<Columns>
<asp:BoundField DataField="Emp_Name" HeaderText="Employee Name" HeaderStyle-Width="150px" />
<asp:BoundField DataField="Emp_job" HeaderText="Job title" HeaderStyle-Width="150px" />
<asp:BoundField DataField="Emp_Dep" HeaderText="Department" HeaderStyle-Width="150px" />
<asp:TemplateField ItemStyle-Width="40px">
<HeaderTemplate>
<asp:CheckBox ID="chkboxSelectAll" runat="server" onclick="CheckAllEmp(this);" />
</HeaderTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemTemplate>
<asp:CheckBox ID="chkEmp" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Using HeaderTemplate of gridview I had added checkbox and also added in Itemtemplate of same column.

--> 그리드 헤더템플릿을 사용 할 때 체크박스를 추가하고 또한 같은 컬럼에 아이템 템플릿을 추가한다.

 

 

Select and deselect using Client side

--> 클라이언트 사이드를 사용하여 선택/선택 해제


I’m loading the few sample employee records in gridview to select/deselect all rows. Below javascript CheckAllEmp function will do select and deselect when check and uncheck in header checkbox.

--> 그리드 뷰에 전체 선택/선택해제 할 수 있는 몇개의 직원 샘플 레코드 기록 loading. 아래 자바스크립트 CheckAllEmp 함수가 선택/선택해제 할 때 헤더 체크박스를 체크/체크해제 할 것이다.

Call this function in gridview headertemplate, checkbox onclick event as shown above.

--> 그리드뷰 헤더템플릿 안의 함수 호출. 체크박스 onclick 이벤트 위에서 보여진 것 처럼.


<script type="text/javascript" language="javascript">
function CheckAllEmp(Checkbox) {
var GridVwHeaderChckbox = document.getElementById("<%=GridVwHeaderChckbox.ClientID %>");
for (i = 1; i < GridVwHeaderChckbox.rows.length; i++) {
GridVwHeaderChckbox.rows[i].cells[3].getElementsByTagName("INPUT")[0].checked = Checkbox.checked;
}
}
</script>


Above javascript code will get gridview client id and loop the each row and get the checkbox id which is available in itemTemplate and make it select/deselect rows. This is the one of the way using client side script.

--> 위의 자바 스크립트 코드는 GridView에 클라이언트 ID를 얻고, 각각의 열의 ItemTemplate에서 사용할 수있는 체크박스 ID를 얻고 선택/선택 해제 할 것입니다. 이는 클라이언트 사이드 스크립트에서 사용하는 방법의 하나이다.

 

 

Select and deselect using Server side

--> 서버단을 사용하여 선택/선택 해제

 

Same functionality we can able to do with server side also. To do this make the changes in HeaderTemplate as like below.

--> 같은 기능을 서버 측에서도 할 수 있다. 아래의 헤더 템플릿을 변경한다.

 

<asp:TemplateField ItemStyle-Width="40px">
                        <HeaderTemplate>
                            <asp:CheckBox ID="chkboxSelectAll" runat="server" AutoPostBack="true" OnCheckedChanged="chkboxSelectAll_CheckedChanged" />
                        </HeaderTemplate>
                        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        <ItemTemplate>
                            <asp:CheckBox ID="chkEmp" runat="server"></asp:CheckBox>
                        </ItemTemplate>
                    </asp:TemplateField>

 

Make it autopostback as true and create OnCheckedChanged event in checkbox and add the below code in chkboxSelectAll_CheckedChanged event in code behind part.

--> autopostback 을 true로 만들고, 체크박스에 OnCheckedChanged 이벤트를 생성하고 아래 코드를 chkboxSelectAll_CheckedChanged 이벤트 안 코드비하인드 파트에 추가.

 

protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox ChkBoxHeader = (CheckBox)GridVwHeaderChckboxSrvr.HeaderRow.FindControl("chkboxSelectAll");
            foreach (GridViewRow row in GridVwHeaderChckboxSrvr.Rows)
            {
                CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkEmp");
                if (ChkBoxHeader.Checked == true)
                {
                    ChkBoxRows.Checked = true;
                }
                else
                {
                    ChkBoxRows.Checked = false;
                }
            }
        }

 

Above checked changed event will get the header checkbox id and if header checkbox is checked then find all rows checkbox id and make it all select else deselect all rows

--> 위에 Checked Change 이벤트에서 헤더 체크박스의 아이디를 얻고 만약 헤더 체크 박스의 체크가 됐다면 모든 로우의 체크박스 아이디를 얻고 모두 선택 또는 선택해제.

 

 


I have attached sample code for this. Thank you for reading this article and hope you enjoyed this article. Please provide your feedback and suggestions.

 

 

 

728x90
728x90

출처 사이트 URL: http://www.aspsnippets.com/Articles/GridView-with-CheckBox-Get-Selected-Rows-in-ASPNet.aspx

 

 

 

GridView with CheckBox: Get Selected Rows in ASP.Net

 

HTML Markup
The HTML Markup consists of an ASP.Net GridView with CheckBox in the TemplateField column of GridView. There’s a Button that will fetch the selected rows of GridView and will display the same in another GridView below it.
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="chkRow" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
            <ItemTemplate>
                <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<br />
<asp:Button ID="btnGetSelected" runat="server" Text="Get selected records" OnClick="GetSelectedRecords" />
<hr />
<u>Selected Rows</u>
<br />
<asp:GridView ID="gvSelected" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
    </Columns>
</asp:GridView>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
 
VB.Net
Imports System.Data
 
 
Binding the GridView
I have made use of DataTable with some dummy values for this article.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name"), new DataColumn("Country") });
        dt.Rows.Add("John Hammond", "Canada");
        dt.Rows.Add("Rick Stewards", "United States");
        dt.Rows.Add("Huang He", "China");
        dt.Rows.Add("Mudassar Khan", "India");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As New DataTable()
        dt.Columns.AddRange(New DataColumn(1) {New DataColumn("Name"), New DataColumn("Country")})
        dt.Rows.Add("John Hammond", "Canada")
        dt.Rows.Add("Rick Stewards", "United States")
        dt.Rows.Add("Huang He", "China")
        dt.Rows.Add("Mudassar Khan", "India")
        GridView1.DataSource = dt
        GridView1.DataBind()
    End If
End Sub
 
 
Fetching Selected Records from GridView
On the click of the Button the following event handler is executed. A loop is executed over the GridView Data Rows and CheckBox is referenced. If the CheckBox is checked then the name and country are fetched from the BoundField and the TemplateField Label respectively.
The selected rows are then added to a DataTable which is then bound to the other GridView which displays the selected records
C#
protected void GetSelectedRecords(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name"), new DataColumn("Country") });
    foreach (GridViewRow row in GridView1.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
            if (chkRow.Checked)
            {
                string name = row.Cells[1].Text;
                string country = (row.Cells[2].FindControl("lblCountry") as Label).Text;
                dt.Rows.Add(name, country);
            }
        }
    }
    gvSelected.DataSource = dt;
    gvSelected.DataBind();
}
 
VB.Net
Protected Sub GetSelectedRecords(sender As Object, e As EventArgs)
    Dim dt As New DataTable()
    dt.Columns.AddRange(New DataColumn(1) {New DataColumn("Name"), New DataColumn("Country")})
    For Each row As GridViewRow In GridView1.Rows
        If row.RowType = DataControlRowType.DataRow Then
            Dim chkRow As CheckBox = TryCast(row.Cells(0).FindControl("chkRow"), CheckBox)
            If chkRow.Checked Then
                Dim name As String = row.Cells(1).Text
                Dim country As String = TryCast(row.Cells(2).FindControl("lblCountry"), Label).Text
                dt.Rows.Add(name, country)
            End If
        End If
    Next
    gvSelected.DataSource = dt
    gvSelected.DataBind()
End Sub
 

GridView with CheckBox: Get Selected Rows in ASP.Net

GridView with CheckBox: Get Selected Rows in ASP.Net

728x90
728x90


SqlConnection : SQL Server 데이터베이스에 대한 열린 연결을 나타냅니다. 이 클래스는 상속될 수 없습니다.

SqlConnection 개체는 SQL Server 데이터 소스에 대한 고유 세션을 나타냅니다. 클라이언트/서버 데이터베이스 시스템의 경우, 이 개체는 서버에 대한 네트워크 연결에 해당합니다. Microsoft SQL Server 데이터베이스에 연결할 때 SqlConnection을 SqlDataAdapter 및 SqlCommand와 함께 사용하여 성능을 향상시킵니다. 모든 타사 SQL 서버 제품 및 다른 OLE DB 지원 데이터 소스의 경우 OleDbConnection을 사용합니다.
SqlConnection의 인스턴스를 만드는 경우 모든 속성이 초기 값으로 설정됩니다. 이러한 값에 대한 목록은 SqlConnection 생성자를 참조하십시오.
SqlConnection이 범위를 벗어나면 계속 열려 있습니다. 따라서 동일하게 작동하는 Close 또는 Dispose를 호출하여 명시적으로 연결을 닫아야 합니다. Close와 Dispose는 기능이 동일합니다. 연결 풀링 값 Pooling이 true 또는 yes로 설정되어 있으면 기본 연결이 연결 풀로 반환되지만, Pooling이 false 또는 no로 설정되어 있으면 서버에 대한 기본 연결이 실제로 닫혀 있습니다.
연결이 항상 닫혀 있도록 하려면 using 블록 안에서 연결을 엽니다. 이렇게 하면 코드에서 해당 블록을 종료할 때 연결이 자동으로 닫힙니다. 

참고 페이지 : http://msdn.microsoft.com/ko-kr/library/system.data.sqlclient.sqlconnection%28v=vs.80%29.aspx



SqlCommand : SQL Server 데이터베이스에 대해 실행할 Transact-SQL 문이나 저장 프로시저를 나타냅니다. 이 클래스는 상속될 수 없습니다.

SqlCommand의 인스턴스가 만들어지면 초기 값에 읽기/쓰기 속성이 지정됩니다.

DataSet을 사용하지 않고 쓰기, 수정, 삭제 등이 가능하다.

참고 페이지 : http://msdn.microsoft.com/ko-kr/library/system.data.sqlclient.sqlcommand%28v=vs.80%29.aspx



SqlDataAdapter : SqlDataAdapter는 DataSet를 채우고 SQL Server 데이터베이스를 업데이트하는 데 사용할 데이터 명령 집합과 데이터베이스 연결을 나타냅니다. 이 클래스는 상속될 수 없습니다.

SqlDataAdapter는 DataSet와 데이터를 검색하고 저장하는 SQL Server 간의 연결로 사용됩니다. SqlDataAdapter 는 데이터 소스에 대한 적절한 Transact-SQL 문을 사용하여, DataSet의 데이터를 데이터 소스의 데이터와 동일하게 일치시키기 위해 변경하는 Fill과 데이터 소스의 데이터를 DataSet의 데이터와 동일하게 일치시키기 위해 변경하는 Update을 매핑하여 이 연결을 제공합니다.
SqlDataAdapter는 DataSet을 채울 때, 반환된 데이터 저장에 필요한 테이블과 열이 없으면 이를 만듭니다. 그러나 MissingSchemaAction 속성이 AddWithKey로 설정되지 않은 경우 기본 키 정보는 암시적으로 만들어진 스키마에 포함되지 않습니다. FillSchema를 사용하여 이를 데이터로 채우기 전에 SqlDataAdapter가 기본 키 정보를 포함하는 DataSet의 스키마를 만들도록 할 수 있습니다. 자세한 내용은 DataSet에 기존 제약 조건 추가을 참조하십시오.
SqlDataAdapter는 SqlConnection 및 SqlCommand와 함께 사용되어, SQL Server 데이터베이스에 연결할 때의 성능을 향상시킵니.
또한 SqlDataAdapter에는 SelectCommand, InsertCommand, DeleteCommand, UpdateCommand 및 TableMappings 속성이 들어 있어서 데이터를 쉽게 로드하고 업데이트할 수 있습니다.
SqlDataAdapter의 인스턴스가 만들어지면, 읽기/쓰기 속성이 초기 값으로 설정됩니다. 이러한 값에 대한 목록은 SqlDataAdapter 생성자를 참조하십시오.

참고 페이지 : http://msdn.microsoft.com/ko-kr/library/system.data.sqlclient.sqldataadapter%28v=vs.80%29.aspx


SqlHelper 참고페이지 : http://www.taeyo.pe.kr/Columns/View.aspx?SEQ=85&PSEQ=8&IDX=0



728x90
728x90



ASP.NET의 인증은 PassPort, Windows, Forms, None 등 네가지 종류가 있다.


PassPort : MS 인증

Windows : Windows의 사용자 계정을 기반으로 인증을 처리하는 방식으로 IIS내에 인증을 구성. 안전하지만 IE에서만 지원되고, 모든 사용자들이 windows 계정을 보유하고 있어야 하는 단점. IIS는 네가지 인증 방법[Anonymous, basic, ddigest, windows integrated]을 제공한다.

windows 참고 페이지

- http://blog.naver.com/PostView.nhn?blogId=myfancy&logNo=140021264549

Form : ASP.NET 폼 기반의 인증 사용

None : 인증을 사용하지 않음. 쿠키나 세션을 통해 직접인증.


MemberShip, Role, Profile Provider

- 상황에 따른 서비스 선택 -
1. 회원 가입,수정,탈퇴(블록처리) 및 로그인, 로그인상태처리,비밀번호 찾기,변경과 같은 일반적인 회원관리를 위해서는 MemberShip 서비스를 이용하면 된다.
2. 회원 등급제 운영, 권한 설정,권한별 접근 제어와 같은 회원의 권한관리를 위해서는 Role 서비스를 이용하면 된다.
3. 회원의 기본정보(ID,Password,Email등) 이외에 추가적인 정보를 관리하기 위해서는 Profile 서비스를 이용하면 된다.


참고 페이지

- http://www.mkexdev.net/Article/Content.aspx?parentCategoryID=1&categoryID=11&ID=250

- http://blog.naver.com/PostView.nhn?blogId=ozdamby&logNo=21121021&redirect=Dlog&widgetTypeCall=true

- http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/configuring-a-website-that-uses-application-services-cs

- http://cafe.daum.net/aspdotnet/HAEk/54?docid=8C6QHAEk5420060216102817

- http://hotdogya.blogspot.kr/2009/07/%ED%8E%8Ccustom-membership-provider-2.html


728x90

+ Recent posts