Advertisements
Showing posts with label C-Sharp. Show all posts
Showing posts with label C-Sharp. Show all posts

Friday, May 30, 2014

// // Leave a Comment

HTTP Error 500.23 - Internal Server Error - Solution 2

Hi,

If you keep visiting here, some days ago, I have posted a same post here. The problem is similar again but difference is another way to solve the same problem.
Lets have a look at fresh snapshot.

HTTP Error 500.23 - Internal Server Error

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.

Most likely causes:

  • This application defines configuration in the system.web/httpHandlers section.

Things you can try:

  • Migrate the configuration to the system.webServer/handlers section. You can do so manually or by using AppCmd from the command line - for example, %SystemRoot%\system32\inetsrv\appcmd migrate config "Default Web Site/". Using appcmd to migrate your application will enable it to work in Integrated mode, and continue to work in Classic mode and on previous versions of IIS.
  • If you are certain that it is OK to ignore this error, it can be disabled by setting system.webServer/validation@validateIntegratedModeConfiguration to false.
  • Alternatively, switch the application to a Classic mode application pool - for example, appcmd set app "Default Web Site/" /applicationPool:"Classic .NET AppPool". Only do this if you are unable to migrate your application.
(Set "Default Web Site" and "Classic .NET AppPool" to your application path and application pool name)

If you are still confused about the previous post, here is the link.
http://www.pyarb.com/2014/02/http-error-50023-internal-server-error.html

Problem

Last time, we received the similar problem while debugging from Visual Studio, this time it is produced by IIS itself after publishing.

Solution

We will add small piece of code into web.config file. This can be done using two methods. Either you open any text-editor (notepad) with Administrator Privilege and open web.config from your IIS root or change the setting in Visual Studio web.config and publish again. What you want to is totally on you.
Piece of Code:
......
<system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
    </system.webServer>
</configuration>


Place this code inside configuration node. Also, this will not harm you in case of security, This will just tell not to check such settings which are not required.
Thanks for reading. Do not forget to share or provide feedback.
+John Bhatt

Read More

Thursday, January 16, 2014

// // 1 comment

Export to Word from GridView in ASP.NET

Hi,

Today, I am going to continue our GridView tricks series ahead and posting a nice and useful feature. For all list of GridView articles we have written here, you can search for GridView in search box. As I have previously written about Exporting data to Excel from GridView, this is about exporting GridView to Microsoft Word which is another most used document format and needed in most cases.
Lets create a design as below.
I have just dragged and dropped a gridview control and used autoformat to make GridView look some better. 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1 {
            text-align: justify;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1 class="auto-style1">
        Export to Word 
    </h1>
        <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" Width="590px">
            <FooterStyle BackColor="White" ForeColor="#000066" />
            <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
            <RowStyle ForeColor="#000066" />
            <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#007DBB" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#00547E" />
        </asp:GridView>
        <br />
        <asp:Button ID="Button1" runat="server" Font-Bold="True" OnClick="Button1_Click" Text="Export to Word" />
    </div>
    </form>
</body>
</html>

Now bind data to this gridview from backend.

 protected void Page_Load(object sender, EventArgs e)
    {
        string ConString = "Server=.\\sqldb;database=Store;integrated security=true;";
        SqlConnection con = new SqlConnection(ConString);
        string QueryText = "SELECT DISTINCT Products.ProductName, Brands.BrandName, Category.CategoryName, 
Products.UnitPrice, Products.UnitsInStock from products,brands,Suppliers,Category 
where Products.BrandID=Brands.BrandID and Products.CategoryID=Category.CategoryID;";

        SqlDataAdapter adp = new SqlDataAdapter(QueryText, con);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();
    }
Let's view page in Browser. You must see data from your database. Mine query has resulted below data in grid.
Perfect, now its time to do the important stuff. Lets write code for Export Button. Double click in button to create a method and automatically bind event with control. Now write below code in backend.

 public override void VerifyRenderingInServerForm(Control control)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment;filename=Products.doc"));        
        Response.ContentType = "application/vnd.ms-word ";
        StringWriter WriterForWord = new StringWriter();
        HtmlTextWriter HTMLWriter = new HtmlTextWriter(WriterForWord);
        GridView1.AllowPaging = false;
        GridView1.DataBind();
        GridView1.RenderControl(HTMLWriter);
        Response.Output.Write(WriterForWord.ToString());
        Response.Flush();
        Response.End();
    }

Its time to check our code, Click on Export to Word button. I have attached snapshot of Firefox because it prompts user.
You can save file or just click on Open with your word processor software. I am using Microsoft Word here.
Did you read our previous Export to Excel tutorial? What are the similarities between exporting to Word and Excel?
I am leaving with a question, if you know, leave a reply below.
Thanks for reading . Do not forget to say thanks or plus1 or provide feedback.
+John Bhatt 
Read More

Wednesday, January 15, 2014

// // Leave a Comment

Custom Message when no rows in GridView

Hi,
Lets get back to ASP.NET series and work with GridView once again. We have previously done following jobs with GridView.
You are suggested to read above posts before reading this post.

Objective

 If you are a ASP.NET developer, you have to work with GridView control every day. In a SQL powered website, this is a must have control and almost every developer uses it. It grabs data from Data Source defined and show in tabular format with added CSS and other features.
But some features are disabled by default, you have to turn them on. Suppose you have no data to display, GridView control simply disappears, your user will not see any design or message. To overcome this, GridView control has a builtin feature that can tell user that there is no data in that case, we have to just turn it on and customize message.

Design

Lets see a below design.
Lets create a SQL Table as below structure.
--Create a Database for temporary purpose.
CREATE DATABASE TestDatabase;
--Use newly created database for forther queries.
USE testdatabase;
--Create a Simple table with 4 columns
CREATE TABLE TestTable
(
StudentID int PRIMARY KEY Identity(100,1),
StudentName nvarchar(150),
CourseName nvarchar(100),
ContactDetails nvarchar(500) 
);
And bind gridview with above table which is empty. Double click on any empty location of Page to go to Page_Load event or just press F7 key to switch between aspx page and Code behind page.
Code as below is suffcient for this task, you can also go for graphical method.
//Include namespaces for DataTable and SQL access.
using System.Data;
using System.Data.SqlClient;

protected void Page_Load(object sender, EventArgs e)
    {
        string ConString = "Server=.\\sqldb;database=testdatabase;integrated security=true;";
        SqlConnection con = new SqlConnection(ConString);
        SqlDataAdapter adp = new SqlDataAdapter("SELECT * from TestTable", con);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();
    }
Lets view it on browser.
  • Question : Where is our GridView? We have added and binded it with database. 
  • Answer   : Oh! There is no data in table, so it is blank and hidden to free space.  
  • Question : Does user knows about this?
  • Answer   : No, every user might not be familier to ASP.NET and web programming. He will just think some fool has designed page and he forgot to add content in this place. 
So the requirement is to tell user in a familier language that there is no data. So that he can tell you are smart and feel happy with website/application. 

Putting Error Message

We have a attribute property of GridView called EmptyDataText inside Appearance section. Lets have a look at below screenshot.
You can write your error message in case of Empty Data in that textbox or you can simply add a property in GridView code and write its value as below.
<asp:GridView ID="GridView1" runat="server"  
    EmptyDataText="Sorry! There is no data present. Please add or wait for others to enter record."
    EmptyDataRowStyle-ForeColor="Red"  EmptyDataRowStyle-BorderStyle="Solid">

I have added two more attributes named EmptyDataRowStyle-ForeColor which will assign "Red" color as its text color and also EmptyDataRowStyle-BorderStyle attribute which will put a solid border around table. Now save page and view in browser. This will display output as below.


I think this is the actually we wanted to do. Now lets add a record in SQL table and refresh page.
INSERT INTO TestTable VALUES ('John Bhatt','M. Tech','john@johnbhatt.com');

Conclusion

So we can say that, adding EmptyDataText and style for EmptyDataRow does not affect any or our design for normal view.

Do not forget to share and like if you found this helpful. Saying a thank will encourage me. If you find are mistakes and errors in above code and tutorial, please report by leaving a comment here. We will try to rectify and help other members.

+John Bhatt 
Read More

Wednesday, December 4, 2013

// // 2 comments

GridView with Fixed Header & Scroll Bar

Hi,

In previous posts, I have completed two important topics of GridView.
  1. Paging in GridView
  2. Scroll Bars in GridView
Today, Lets learn another new and important trick with GridView, i.e. Fixed Headers. When we have to scroll through GridView, then there is must have feature that is Fixed Header. On recent post I have written about Fixed Headers in Excel, did you get chance to read them. We are doing exactly same task here. But here we do not have "Fix Pane" as in Excel anywhere. Lets do this with simple CSS and some enhance with code-behind.

Also, Today I am using Manual method of GridView creation, in previous demos and posts, I have used Drag & Dropped GridView control. Today here is manually coded GridView. 
Lets see code for ASPX page.
            <h2 align="center">GridView with Fixed Header</h2>
            <div style="height: 400px; overflow: auto" align="center">
                <asp:GridView ID="gvDistricts" runat="server" HeaderStyle-CssClass="FixedHeader" HeaderStyle-BackColor="YellowGreen" 
                    AutoGenerateColumns="false" AlternatingRowStyle-BackColor="WhiteSmoke" OnRowDataBound="gvDistricts_RowDataBound">
                    <Columns>
                        <asp:TemplateField HeaderText="District ID" HeaderStyle-Width="80px" ItemStyle-Width="80px">
                            <ItemTemplate>
                                <asp:Label ID="lblDistID" runat="server" Text='<%#Eval("DistID")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="District Name" HeaderStyle-Width="120px" ItemStyle-Width="120px">
                            <ItemTemplate>
                                <asp:Label ID="lblDistName" runat="server" Text='<%#Eval("DistName")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Description" HeaderStyle-Width="200px" ItemStyle-Width="200px">
                            <ItemTemplate>
                                <asp:Label ID="lblDistDesc" runat="server" Text='<%#Eval("DistDesc")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>

In above design, Notable code is style for DIV which will make this GridView scrollable if its height exceeds than 400px. Another notable code is HeaderStyle-CssClass="FixedHeader". This line of code will apply a custom CSS Class named FixedHeader which we will create in while to do the task required. Before doing this lets bind this GridView with Data. Lets move to Back-end.
I am using data from a SQL table, which simply contains, DistrictID, DistName, DistDesc as its field and approx 25 records filled.

We have nothing to do more here. So simply write the databind code inside Page_Load Event.

protected void Page_Load(object sender, EventArgs e)
    {
        string ConStr = "Data Source=.\\sqldb;Initial Catalog=ShikshaNet;Integrated Security=True";
        if (!IsPostBack)
        {
            string Query = "SELECT * FROM Districts";
            SqlConnection con = new SqlConnection(ConStr);
            SqlDataAdapter adp = new SqlDataAdapter(Query, con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            gvDistricts.DataSource = dt.DefaultView;
            gvDistricts.DataBind();
        }
    }
Now lets loot at browser to know how it looked.
 Perfect as designed. Lets scroll it and look for headers.

Oh! no, Headers are not visible. Lets start what we left at beginning. Add some style to GridView. Just navigate inside Head section of HTML and then add below code. This is stylesheet, you can customize as your requirement, but remember to change your Class name in GridView also if you are changing class name here.
<style type="text/css">
        .FixedHeader {
            position: absolute;
            font-weight: bold;
        }      
    </style>

OK, Lets refresh browser to see the changes.
 On scrolling,
Perfect, Headers are on top. But there is some problem. If you noticed, First record of GridView is not visible. It has dis-appeared. To make that record visible. Lets use a trick. Write some code in RowDataBound Event of GridView.

   protected void gvDistricts_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowIndex == 0)
                e.Row.Style.Add("height", "50px");
        }
    }
We just told Server to add some space if the RowIndex is 0 means first row of GridView should have atleast double space so that the value can be visible.
Lets see the output.

Bingo! You have created a perfect and complete GridView with Fixed Headers. You can use this code and it works fine even used with Paging across multiple browsers.

Thanks to +Amit Jain for the Top row fix which he has posted in his blog at Scrollable GridView With Fixed Headers Asp.Net.
If you found this post useful or helpful, or you have some suggestions to make, please post as comment or send me message on Google+ also.
+John Bhatt 


Tags: Gridview, ASP.NET, Tutorials by John Bhatt, P.Yar.B Complex, Fixed, Freeze, Headers, CSS, C-Sharp, Scrollbar, Tricks
Read More

Wednesday, November 13, 2013

// // Leave a Comment

Pagination in GridView

Hi,
Simply we will learn here how to Apply Pagination in ASP.NET GridView Control.
Directly to Code:
In ASPX page, enable paging in GridView.

<asp:GridView ID="gvAllPOD" runat="server" AutoGenerateColumns="false" 
AlternatingRowStyle-BackColor="LightSeaGreen" HeaderStyle-Font-Bold="true" 
AllowPaging="true" PageSize="20" onpageindexchanging="gvAllPOD_PageIndexChanging">

In Above Code, we Automatically Generated Columns from DataSource Then AllowPaging = True, so that GridView Data can be Paged, Also We defined PageSize that what amount of Records whould display in Page.
To Apply Pagination, RIght Click in GridView and Choose Properties > Events. Choose PageIndexChanged event and Place Following code in ASPX.CS Page.
protected void gvAllPOD_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvAllPOD.PageIndex = e.NewPageIndex;
        BindGVAllPOD();
    }

Now Check on your Page. What is Happening on Clicking Page Number. You can comment if some queries on above code.
John Bhatt
Glad to Know, Free to Share

Tags: Pagination, Paging, GridView, ASP.NET, Disply data in Page, Tutorial bt John Bhatt
Read More

Sunday, October 21, 2012

// // 2 comments

List All SQL Server Instances in Combo (Windows Form) - Part-2

Hello Friends,
On the Previous Post on this series, I have told you the code and procedure upto Connect Button. Hope you have been through it and enjoyed that. If not, please read below post before moving ahead. http://www.prithviraj.com.np/2012/10/list-all-sql-server-instances-in-combo_9.html
Today, I am going to share rest of the Code for Listing Database, Tables Inside Database and Columns and apply them with Operator and simply perform Select Operation from database and list the Result in DataGrid. Let's look the Design you have previously saw when making connection.



In above design,
In Database Combo, we will list all database from Connected Server. Then in Table Combo, we will list all Tables of Selected Database and in Column Combo all columns of Selected Table.

Lets Begin the Code. On Button Click and Successful Connection, we will load all database names in Database Combo. Actually we have did it earlier.
Lets have look at this Code:
comboBox2.Items.Clear();
                   if (checkBox1.Checked == true)
                   {
                       ConStr = "Data Source = " + comboBox1.Text.ToString() + ";Integrated Security = true;";
                   }
                   else
                   {
                       ConStr = "Data Source = " + comboBox1.Text.ToString() + ";UID=" + textBox1.Text + ";pwd=" + textBox2.Text + ";";
                   }
                   SqlConnection Conexion = new SqlConnection(ConStr);
                   Conexion.Open();
                   label9.Visible = false;
                   panel2.Visible = false;
                   button2.Visible = true;
                   panel1.Visible = true;
                   groupBox1.Visible = true;
                   DataTable tblDatabases = Conexion.GetSchema("Databases");
 
                   for (int i = 0; i <= tblDatabases.Rows.Count - 1; i++)
                   {
                       comboBox2.Items.Add(tblDatabases.Rows[i][0].ToString());
                   }
                   Conexion.Close();

This is code from earlier post.
Now Lets see the Code on SelectedIndex Change event of Database Combo (Combobox2).
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBox3.Items.Clear();
            SqlConnection conx = new SqlConnection(ConStr + "Database ="+comboBox2.Text.ToString()+";");
            conx.Open();
            DataTable tblTables = conx.GetSchema("Tables");
            for (int i = 0; i <= tblTables.Rows.Count - 1; i++)
            {
                comboBox3.Items.Add(tblTables.Rows[i][2].ToString());
            }
            conx.Close();
        }
Here we are creating Connection String Everytime, because, It is changing every-time. Now this code will list all the Tables inside Database in Table Combo (combobox3): Code:
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBox4.Items.Clear();
            SqlConnection conx = new SqlConnection(ConStr + "Database =" + comboBox2.Text.ToString() + ";");
            conx.Open();
            string tableName = comboBox3.SelectedItem.ToString();
            SqlDataAdapter adp = new SqlDataAdapter("select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = '"+comboBox3.SelectedItem.ToString()+"'",conx);
            DataTable tblColumns = new DataTable();
            adp.Fill(tblColumns);
            for (int i = 0; i <= tblColumns.Rows.Count - 1; i++)
            {
                comboBox4.Items.Add(tblColumns.Rows[i][3].ToString());
            }
            conx.Close();
        }

Now above code will make all Columns of Selected table from database.
Now Directly move to Keyword TextBox textchange event which will load data as you type.
private void textBox3_TextChanged(object sender, EventArgs e)
        {
            string QueryCon = ConStr;
            if (comboBox5.Text.ToString() == "like")
            {
                QueryStr = "SELECT * FROM " + comboBox3.Text.ToString() + " WHERE " + comboBox4.Text.ToString() + " " + comboBox5.Text.ToString() + " '%" + textBox3.Text + "%'";
            }
            else
            {
                QueryStr = "SELECT * FROM " + comboBox3.Text.ToString() + " WHERE " + comboBox4.Text.ToString() + " " + comboBox5.Text.ToString() + " '" + textBox3.Text + "'";
            }
            TxtQueryBox.Text = ConStr + "Database=" + comboBox2.Text.ToString() + ";"+"\n" + QueryStr;
            SqlDataAdapter adp = new SqlDataAdapter(QueryStr, ConStr+"Database="+comboBox2.Text.ToString()+";");
            DataSet ds = new DataSet();
            adp.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0];
        }

This will load data in GridView automatically. Lets see a snapshot once again with Result.
All the Best, Enjoy....
Read More

Wednesday, October 10, 2012

// // Leave a Comment

List All SQL Server Instances in Combo (Windows Form)


Hi,

I was checking my Old Projects and Like to share a simple example with. Why not to create a SQL Management Application.

How we would do this? What is our objective?

Lets be clear.
We will List All SQL Server Instances available in Network into Application.
Then We will connect to Server using Windows Authentication or SQL Server Authentication.
After successfull authentication ,
We will list all databases in Instance.
After Database, we will List All Tables in Database,
After Database , we will list All Columns in Selected table.
We will place a Create button next to Database, Table list box also.
After selecting a Column, we provided a Filter (operator) and parameters in box.
Which will fetch data and display in DataGridView.

First we Designed a Following Screen.


In Servers List we have to Load All List of Servers and Connect. We have Options for Username and Password and also a Checkbox for Integrated Security (Windows Authentication).
Lets See the Code in Form Load.
Namespace to Include:
using System.Data.Sql;
using System.Data.SqlClient;

Now Form_Load Event Code
private void Form1_Load(object sender, EventArgs e)
        {
            panel1.Visible = false;
            groupBox1.Visible = false;
            label9.Visible = true;
            label9.TextAlign = ContentAlignment.MiddleCenter;
            SqlDataSourceEnumerator SerInstances = SqlDataSourceEnumerator.Instance;
            DataTable SerNames = SerInstances.GetDataSources();
            for (int i = 0; i <= SerNames.Rows.Count - 1; i++)
            {
                comboBox1.Items.Add(SerNames.Rows[i][0].ToString()+"\\"+SerNames.Rows[i][1].ToString());
            }
        }

Description of Above Code: We have placed rest design in Panel and Groupbox so we set that invisible on Form Load. Please Make a Conncetion First.. is Label9 and we set is Visible and aligned. Now main task is to List Sql Servers on Network. For this we used SqlDataSourceEnumerator class. In Next Line we take a DataTable and stored ServerInstances into that. Rest is Simple, We added all items into Listbox. Column 0 contains Machine name and Column 1 contains Instance Name. So we combined that at the Time of Adding to ComboBox Control. Now Click the Connect Button:
 private void button1_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true && textBox1.Text.Trim().Length > 0)
            {
                MessageBox.Show("Please Uncheck Integrated Security or Clear UserName!", this.Text + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (checkBox1.Checked == false && textBox1.Text.Trim().Length == 0)
            {
                MessageBox.Show("Please Check Integrated Security or Enter UserName!", this.Text + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
 
            else if (textBox1.Text.Trim().Length > 0 && textBox2.Text.Trim().Length == 0)
            {
                errorProvider1.SetError(textBox2, "Please enter password for Username = " + textBox1.Text + "!");
            }
            else if (comboBox1.Text.Trim().Length == 0)
            {
                MessageBox.Show("Please select Server from List. If You can not see any Instance in Servers Combobox, Contact your Network Administrator!", this.Text + " - Message", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                errorProvider1.Clear();
                if (MessageBox.Show("Connection Successfull!, You are Now Connected to Server: " + comboBox1.Text.ToString() + "!", this.Text + " - Alert", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK)
                {
                    comboBox2.Items.Clear();
                    if (checkBox1.Checked == true)
                    {
                        ConStr = "Data Source = " + comboBox1.Text.ToString() + ";Integrated Security = true;";
                    }
                    else
                    {
                        ConStr = "Data Source = " + comboBox1.Text.ToString() + ";UID=" + textBox1.Text + ";pwd=" + textBox2.Text + ";";
                    }
                    SqlConnection Conexion = new SqlConnection(ConStr);
                    Conexion.Open();
                    label9.Visible = false;
                    panel2.Visible = false;
                    button2.Visible = true;
                    panel1.Visible = true;
                    groupBox1.Visible = true;
                    DataTable tblDatabases = Conexion.GetSchema("Databases");

                    for (int i = 0; i <= tblDatabases.Rows.Count - 1; i++)
                    {
                        comboBox2.Items.Add(tblDatabases.Rows[i][0].ToString());
                    }
                    Conexion.Close();
                }
            }
        }

Description of Code: We Put some Validation and Message box to make some user friendly environment. After getting Proper Username and password, we make a Connection String and Used Username and password in Connection String. We build a connection, Make Servers List, Username and password and Connect button invisible and Disconnect button Visible. Then First we loaded all Databases of Selected Instance using Connection.GetSchema() method. How it look after connecting.


For now, its your turn to code something for this. I'll be back soon with Rest Part of This Program. Comments are Welcome. Feedback keep the Important Role in Improvement. So Expecting those from you. Happy Learning!

John Bhatt
Glad to Know, Free to Share.....
Read More

Wednesday, September 19, 2012

// // Leave a Comment

File Upload Control with File Type Filter

Hi,

We are going to learn how to upload a File using FileUpload Control in ASP.NET.

ASPX Code

We Placed a FileUpload Control and a button to Click.
<asp:FileUpload ID="FileUpload1" runat="server"  /> 
<asp:Button ID="BtnUpload" runat="server" Text="Upload File" onclick="BtnUpload_Click" />

Back-end Code

Now BtnUpload_Click event in .cs page.
We are going to Upload only Picture (.JPG file or .BMP file).
 
protected void BtnUpload_Click(object sender, EventArgs e)
    {
       string sSiteFolder = "ResumeFolder";
       string sRealPath = Server.MapPath(sSiteFolder);
       if (!Directory.Exists(sRealPath))
           Directory.CreateDirectory(sRealPath);
       string CompletePath = sRealPath + FileUpload1.FileName;
       string FileExt = CompletePath.Substring(CompletePath.IndexOf("."));
       switch (FileExt)
         { 
          case ".jpg":
                FileUpload1.SaveAs(sRealPath + FileUpload1.FileName);
                break;
          case ".JPG":
                FileUpload1.SaveAs(sRealPath + FileUpload1.FileName);
                break;
          case ".bmp":
                FileUpload1.SaveAs(sRealPath + FileUpload1.FileName);
                break;
          case ".BMP":
                FileUpload1.SaveAs(sRealPath + FileUpload1.FileName);
                break;
         }
     }
Enjoy...
John Bhatt
Read More

Wednesday, September 12, 2012

// // Leave a Comment

Pagination with DataList

Hi,
As we know, DataList is the most versatile Data Bound Control available in ASP.NET. Where you can display data as per your need in your required style, direction etc.
But there is some problem also. There is no option to Paginate the Data Loaded in DataList directly. In case we have too many records, we can not display all them in One Page without paginating.

To escape from this situation, Developers move to GridView, which has easy support for Paginating data.

Today, we will learn How to Paginate DataList data in Simple steps.


First create a DataList as per your requirement. I made like below which is quite simple.





Lets place Next and Previous Buttons for Navigation. Code for above design is below:

Code in ASPX Page (Design)

<asp:DataList ID="DataList1" runat="server" Height="194px" Width="174px"
oneditcommand="DataList1_EditCommand"
oncancelcommand="DataList1_CancelCommand"
onupdatecommand="DataList1_UpdateCommand" DataKeyField="eno">
<HeaderTemplate>

<table width="450" border="2">
<tr>
<th>Employee Name </th>
<th>Designation </th>
<th>Salary </th>
<th>
Edit
</th>
</tr>

</HeaderTemplate>
<EditItemTemplate>
<tr>
<td>
<asp:TextBox ID="txtEname" Text='<%#Eval("ename")%>' runat="server" />
</td>
<td>
<asp:TextBox ID="txtJOb" Text='<%#Eval("job")%>' runat="server" />
</td>
<td>
<asp:TextBox ID="txtSal" Text='<%#Eval("sal")%>' runat="server" />
</td>
<td>
<asp:LinkButton ID="lnk2" runat="server" Text="Update" CommandName ="Update" />
</td>
<td>
<asp:LinkButton ID="LinkButton1" runat="server" Text="Cancel"
CommandName ="Cancel" />
</td>
</tr>

</EditItemTemplate>
<ItemTemplate>
<tr>
<td><%#Eval("ename")%></td>
<td><%#Eval("job")%></td>
<td><%#Eval("sal")%></td>
<td>
<asp:LinkButton ID="lnk1" CommandName="Edit" Text="Edit !" runat="server" />
</td>
</tr>

</ItemTemplate>

<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>
<br />
<table class="style1">
<tr>
<td class="style2">
<asp:LinkButton ID="LinkButton2" runat="server" onclick="LinkButton2_Click">Next</asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="LinkButton3" runat="server" onclick="LinkButton3_Click">Previous</asp:LinkButton>
</td>
</tr>
</table>




Now Lets to to Backend. ASPX.CS Page (Code Behind):





protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CurrentPageIndex = 0;
showData();
}
}
int pg = 0;
void showData()
{
PagedDataSource pgd = new PagedDataSource();
SqlDataAdapter da = new SqlDataAdapter("select * from emp", "Data Source=.\\SQLDB;Database=Test1;Integrated Security=True");
DataSet ds = new DataSet();
da.Fill(ds);

pgd.DataSource = ds.Tables[0].DefaultView;
pgd.CurrentPageIndex = CurrentPageIndex ;
pgd.AllowPaging = true;
pgd.PageSize = 5;

LinkButton2.Enabled = !(pgd.IsLastPage);
LinkButton3.Enabled = !(pgd.IsFirstPage);


DataList1.DataSource = pgd;
DataList1.DataBind();

}

protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = e.Item.ItemIndex;
showData();
}
protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = -1;
showData();
}
protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{

}

public int CurrentPageIndex
{
get
{
if (ViewState["pg"] == null)
return 0;
else
return Convert.ToInt16(ViewState["pg"]);
}
set
{
ViewState["pg"] = value;
}
}

protected void LinkButton2_Click(object sender, EventArgs e) {
CurrentPageIndex++;
showData();
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
CurrentPageIndex--;
showData();
}




Now Let me Describe things happened in above code:




Move to showData() function.








We created a new object of PagedDataSource. Paged data source as name stands clear, paginated data.





Now we wrote Query, Passed in Adapter, Filled DataSet which should be all clear, because it was Basic Task in ADO.NET. Now we gave it CurrentPageIndex. means where is page now.








For this, just look below to a class CurrentPageIndex which is returning value of CurentPageIndex =0 if page is beling Loaded. To check whether page is loaded or postback, we take help of ViewState. If ViewState["pg"] == null, On Page load this will be null because it is just being initiated. On Postback it will pass the Int value stored in it to CurrentPageIndex.








We set Pagination in PagedDataSource true and Define Page size of 5 records per page.


Now Passed PagedDataSource object as Datasource of Datalist.








Now Linkbutton click events, We increased and Decreased value of CurrentPageIndex.








Hope this must be helpful to you. In case of Any problem, correction in code and help, feel free to comment below.





John Bhatt




Glad to Know, Free to Share.....





http://www.johnbhatt.com





Read More

Wednesday, August 29, 2012

// // Leave a Comment

Implement Same WebMethod for AutoComplete in Multiple Textbox

Hi,


While Answering a question at Forum, I wrote this post.


Suppose We have Multiple Textbox in Same Page and we want to Implement AutoSuggest/AutoComplete feature in All Textbox and of same type. Suppose Multiple Google Search Boxes.


For that case, we have separate Textboxs, Separate AutoComplete Extenders and Separate Methods. We are trying to Consume same PageMethod in All Textbox.


Front End Code:

Product One:


DelimiterCharacters="" Enabled="True" ServiceMethod="GetProducts" MinimumPrefixLength="2"
ServicePath="" TargetControlID="TextBox1" UseContextKey="True">

Product Two:


DelimiterCharacters="" Enabled="True" ServicePath="" TargetControlID="TextBox2"
ServiceMethod="GetProducts" MinimumPrefixLength="2" UseContextKey="True">

Product Three:


DelimiterCharacters="" Enabled="True" ServicePath="" TargetControlID="TextBox3"
ServiceMethod="GetProducts" MinimumPrefixLength="2" UseContextKey="True">




BackEnd Code:


[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetProducts(string prefixText, int count, string contextKey)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConToStore"].ConnectionString);
SqlDataAdapter adp = new SqlDataAdapter("Select * from Products where UnitsInStock>0 and ProductName like '%" + prefixText + "%'", con);
DataSet ds = new DataSet();
adp.Fill(ds);
string[] Products = new string[ds.Tables[0].Rows.Count];
for (int j = 0; j <= ds.Tables[0].Rows.Count - 1; j++)
{
Products.SetValue(ds.Tables[0].Rows[j][1].ToString(), j);
}
return Products;
}
Lets Look at the Output.

Hope this will be Helpful.
John Bhatt
Glad to Know, Free to Share.....
http://www.johnbhatt.com

Read More

Saturday, August 18, 2012

// // Leave a Comment

Populate DropDownList Dynamically in ASP.NET (Country-State-District-City)

How to Make a Complete Dropdown and Prevent Inserting Dummy Data from Form.
Disable other Controls when Clicked back to Parent Control:
Drop Down Sequence:
OnLoad
Load Country
On-Change
Load State according to Country
On-Change
Load Dists in State
On-Change
List Cities in Dist.

Code:
 protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
  {
   ddlState.DataSource = res.States(Convert.ToInt16(ddlCountry.SelectedValue));
   ddlState.DataTextField = "StateName";
   ddlState.DataValueField = "StateID";
   ddlState.DataBind(); 
   ddlState.Items.Insert(0, "Select");
   ddlDist.Enabled = false;
   ddlCity.Enabled = false;
  }
 protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{ ddlDist.DataSource = res.Districts(Convert.ToInt16(ddlState.SelectedValue)); ddlDist.DataTextField = "DistName"; ddlDist.DataValueField = "DistID"; ddlDist.DataBind(); ddlDist.Items.Insert(0, "Select"); ddlDist.Enabled = true; ddlCity.Enabled = false; } protected void ddlDist_SelectedIndexChanged(object sender, EventArgs e) { ddlCity.DataSource = res.Cities(Convert.ToInt16(ddlDist.SelectedValue)); ddlCity.DataTextField = "CityName"; ddlCity.DataValueField = "CityID"; ddlCity.DataBind(); ddlCity.Items.Insert(0, "Select"); ddlCity.Enabled = true; }
Preview:
John Bhatt
Glad to Know, Free to Share.....
http://www.johnbhatt.com
Read More

Sunday, July 8, 2012

// // Leave a Comment

State Management in ASP.NET part-1 (Cookies)

Hi,

I am Back with State Management Series.

In this post we are going to Talk about Cookies. After Reading this, you must be able to do following things:
  • Create Cookie
  • Access Cookie
  • Can answer Some Basic Q & A about Cookie
What is Need of Cookie?

Cookies are Required to Store Temporary data in Users system which may be Required during Session or after Session.

How Many Type of Cookie are there?
Cookies are generally of Two Type. Session wide or Persistent. Sessional cookies Expire as soon as User Closed Session means Browser. Persistent cookies expire after Defined Time. This can be Defined at the Time of Creation.

Who Make Cookies?

Cookie is always made by Application (Server) in Users/ Clients Browser and stored in Hard Disk of User. These are used to store Users Customized Appearance, other Values , Login Time etc for future Retrieval so that website can server him better.

Limitations of Cookie?

Cookies are open Invitations to Hackers.

Cookies can only store Little and Only String Type Data.



Now Lets Learn with Coding. First We will Create a Cookie named myCookie and Solve Earlier Problem with the Help of Cookie.
Now Code is Like Below:
protected void Page_Load(object sender, EventArgs e)
{

}
int x; // Made a Variable with Datatype Int for Future Use
HttpCookie myCookie; // Defined a Cookie named myCookie.
protected void Button1_Click(object sender, EventArgs e)
{
x = Convert.ToInt32(TextBox1.Text); // Converted textbox Value which we earlier Did.
myCookie = new HttpCookie("txtValue"); // Assigned Variable myCookie.
myCookie.Value = Convert.ToString(x); // Value assigned to myCookie.
Response.Cookies.Add(myCookie); //This Simple Made a Cookie that will Expire in Session End.
myCookie.Expires = DateTime.Now.AddMinutes(15); // We made is Persistent and stored it for Next 15 minutes.

}
protected void Button2_Click(object sender, EventArgs e)
{

HttpCookie storedCook = Request.Cookies["txtValue"]; // Requested from Server for Cookie
if (storedCook != null)
x = Convert.ToInt32(storedCook.Value); // Converted to Integer again.
TextBox1.Text = Convert.ToString(x * x); // Now Printed Value in Textbox.
}
Now Check....

Don't forget to add me on Google+, +John Bhatt .
Read More
// // Leave a Comment

State Management in ASP.NET

Hi Everybody,


I am once back with a blog/article/tutorial whatever you think/call it.


State Management :


HTTP Protocol is State less protocol. In Simple Language, Each and Every time We send a request to server, this is New to server.

To Understand this ,Suppose you took One Textbox and Two Buttons like in Image below:



Now, the task is To Enter Number in Textbox and Click in First Button to Convert to Integer format and then Click Second button to Print Square of Converted Integer in Textbox. What will you do. Lets look at code what I did here.

protected void Page_Load(object sender, EventArgs e)
{

}
int x;

protected void Button1_Click(object sender, EventArgs e)
{
x = Convert.ToInt32(TextBox1.Text);
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox1.Text = Convert.ToString(x * x);
}


Now what would I get Result on Second Button Click event. Textbox Result will be 0 even I have entered any number. Don't agree, try this at home.


This is Because, at the time of Button2 Click new request is send to server and Initial Value of X is picked from server which is 0.


To Prevent the Loose of Data each time we send request to server, ASP.NET have implemented concept of State Management.

State Management is divided into 2 parts according to Functionality.

1) User Based State Management
  • Cookies
  • QueryStrings
  • ViewState
  • Controls
  • Hidden Fields
2) Server Based State Management
  • Session
  • Application
  • Profile


I am going to Describe all these States step by step in Different Posts.

All the Series has been posted on DotNetSpider at below Link Resources > Keep Reading.
Read More

Friday, June 22, 2012

// // 1 comment

Export to Excel from DataGridView in ASP.NET

Hi,
We are going to learn how to Export GridView data to Microsoft Excel at Runtime.

We are using: ASP.NET Framework 4.0, Visual Studio 2010, SQL Server 2008, C#, XHTML 4.01

 Code for ASPX Page (Front-End) Adding GridView and Columns:

 <asp:GridView ID="gvPros" runat="server" AutoGenerateColumns="false" Width="664px" Font-Names="Calibri"
                    HeaderStyle-Font-Bold="true" AlternatingRowStyle-BackColor="LightGoldenrodYellow" EmptyDataText="No Records Found. Try again by Changing Filter Options.">
                    <Columns>
                        <asp:TemplateField HeaderText="Party Name">
                            <ItemTemplate>
                                <asp:Label ID="lblPartyName" runat="server" Text='<%#Eval("PartyName")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Mode">
                            <ItemTemplate>
                                <asp:Label ID="lblFreight" runat="server" Text='<%#Eval("Division")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Month">
                            <ItemTemplate>
                                <asp:Label ID="lblMonthName" runat="server" Text='<%#Eval("ProMonth")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Total Box">
                            <ItemTemplate>
                                <asp:Label ID="lblTotalBox" runat="server" Text='<%#Eval("ProPkg")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Actual Weight">
                            <ItemTemplate>
                                <asp:Label ID="lblPartyName" runat="server" Text='<%#Eval("ProActWt")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Charged Wt">
                            <ItemTemplate>
                                <asp:Label ID="lblChWt" runat="server" Text='<%#Eval("ProChWt")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Freight">
                            <ItemTemplate>
                                <asp:Label ID="lblFreight" runat="server" Text='<%#Eval("ProFreight")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

Adding Export Link
 <asp:LinkButton ID="lnkExport" runat="server" Text="Export to Excel" onclick="lnkExport_Click"></asp:LinkButton>

Now Code for ASPX.CS Page (BackEnd):


Namespaces :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Text;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;

Data Binding and Export LinkButton Click Event:
void GVProsFill()
    {
        string Query = "Select * from Parties,  Prosperity where Parties.PartyID=Prosperity.ProParty";
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConToSEPL"].ConnectionString);
        SqlDataAdapter adp = new SqlDataAdapter(Query, con);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        gvPros.DataSource = ds.Tables[0];
        gvPros.DataBind();
    }
 
//You have to add an another Event for Export to work properly:
public override void VerifyRenderingInServerForm(Control control) 
     { 
         // Can Leave This Blank. 
     }

protected void lnkExport_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Prosperity.xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        gvPros.AllowPaging = false;
        GVProsFill();
        gvPros.HeaderRow.Style.Add("background-color", "#FFFFFF");
        for (int a = 0; a < gvPros.HeaderRow.Cells.Count; a++)
        {
            gvPros.HeaderRow.Cells[a].Style.Add("background-color", "#507CD1");
        }
        int j = 1;
        foreach (GridViewRow gvrow in gvPros.Rows)
        {
            gvrow.BackColor = Color.White;
            if (j <= gvPros.Rows.Count)
                {
     if (j % 2 != 0)
      {
       for (int k = 0; k < gvrow.Cells.Count; k++)
         {
        gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
         }
      }
    }
   j++;
        }
        gvPros.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }

I will be waiting to Listen from you....
John Bhatt
Read More

Sunday, June 3, 2012

// // Leave a Comment

What is C# and what software are required to run a C# program?

C# 

C# (pronounced see sharp) is a Object Oriented, Component Oriented and Most Advance Programming Language from Microsoft. 
C# code is to be compiled before it Run. You can use C# to Create Windows Applications as well Web Applications. Software you see in General Life are Mostly powered by C#, because if Its Simplicity and Advance Features. There is nothing impossible to do with C#. 


Now as I told earlier, C# source code must be compiled before it to Run. Even If you are creating Windows Application (Desktop based) or Web application (Browser based), you must compile the code. 
You have following Software to to the Job of C# Compiler which are called IDE here and Compiling Task is called Implementation. 
Main is Microsoft Visual C#. This is built in tool in Microsoft Visual Studio Express (Free). 
Mono Project provides Open Source IDE for C# named MonoDevelop.
SharpDevelop is another Open Source Tool.



There are few more applications for Linux and Mac which does the same job as in Windows.





Read More