asp.net,gridview,datagridview,webforms , How can i make excel like grid in asp.net C# Webform


How can i make excel like grid in asp.net C# Webform

Question:

Tag: asp.net,gridview,datagridview,webforms

How can I make a grid like in Excel in ASP.NET WebForms?

I would like rows and coloms where user can enter data and after a click on a save button the data would be inserted into a database.


Answer:

Hope this will help you out to full-fill your requirement.Here I am giving only aspx and c# coding. Create and modify your database and change the code accordingly.Here I am using direct insert statement you can use stored procedure.

Table in Database:-

enter image description here

page.aspx :-

<asp:GridView ID="excelgrd" runat="server" AutoGenerateColumns="false" ShowFooter="true">
            <Columns>
                <asp:BoundField DataField="Slno" HeaderText="SL No" />
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:TextBox ID="txnm" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                 <asp:TemplateField HeaderText="Description">
                    <ItemTemplate>
                        <asp:TextBox ID="txdesc" runat="server"></asp:TextBox>
                    </ItemTemplate>
                      <FooterStyle HorizontalAlign="Right" />
                      <FooterTemplate>
                       <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
                      </FooterTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:Button ID="svbtn" runat="server" Text="Save" OnClick="svbtn_Click" />`

code behind of your page :-

`

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
             bindgrd();//bind your grid
        }
    }
    private void bindgrd()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("Slno", typeof(string)));
        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("Desc", typeof(string)));
        dr = dt.NewRow();
        dr["Slno"] = 1;
        dr["Name"] = string.Empty;
        dr["Desc"] = string.Empty;
        dt.Rows.Add(dr);
        //Store the DataTable in ViewState
        ViewState["CurrentTable"] = dt;
        excelgrd.DataSource = dt;
        excelgrd.DataBind();
    }
    protected void addnewrow()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the TextBox values
                    TextBox tx1 = (TextBox)excelgrd.Rows[rowIndex].Cells[1].FindControl("txnm");
                    TextBox tx2 = (TextBox)excelgrd.Rows[rowIndex].Cells[2].FindControl("txdesc");

                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["Slno"] = i + 1;

                    dtCurrentTable.Rows[i - 1]["Name"] = tx1.Text;
                    dtCurrentTable.Rows[i - 1]["Desc"] = tx2.Text;

                    rowIndex++;
                }
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                excelgrd.DataSource = dtCurrentTable;
                excelgrd.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }

        //Set Previous Data on Postbacks
        SetPreviousData();
    }
    private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox tx1 = (TextBox)excelgrd.Rows[rowIndex].Cells[1].FindControl("txnm");
                    TextBox tx2 = (TextBox)excelgrd.Rows[rowIndex].Cells[2].FindControl("txdesc");
                    tx1.Text = dt.Rows[i]["Name"].ToString();
                    tx2.Text = dt.Rows[i]["Desc"].ToString();

                    rowIndex++;
                }
            }
        }
    }
    protected void svbtn_Click(object sender, EventArgs e)
    {
        foreach(GridViewRow r in excelgrd.Rows)
        {
          string des =(r.FindControl("txdesc") as TextBox).Text;
          string nm = (r.FindControl("txnm") as TextBox).Text;
          try
          {
              con.Open();
              SqlCommand sql = new SqlCommand("insert into test (name,name_desc) values('"+nm+"','"+des+"')", con);
              sql.ExecuteNonQuery();
              sql.Dispose();
          }
          catch (Exception e1)
          {
              string error = e1.ToString();
          }
          finally
          {
              con.Close();

          }

        }
    }
    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        addnewrow();
    }`

Related:


WCF service architecture query


asp.net,architecture,wcfserviceclient
I have an application that consists of a web application, and mutliple windows services, only one windows service is installed depending on what version of the backend sofware is used. Currently, Data is saved by the web app in a database, then the relevant service is installed and this picks...

deployment of a site asp.net and iis


c#,asp.net,iis
I know this is for some of you a stupid question but for me is a real problem. I have never deployed a site before What i have done so far: 1) publish the site from visual studio to a folder. 2) added to iis for testing everything works great...

How to make a website work only with https [duplicate]


asp.net,ssl,https
This question already has an answer here: How to force HTTPS using a web.config file 3 answers How do I make a website to work only with https? Is there any method to make my website work only if the protocol is https? For example let me say http://www.mywebsite.com,...

onSuccess and onFailure doesn't get fired


javascript,c#,asp.net,webmethod,pagemethods
I have used onSuccess and onFailure in my PageMethod call. However neither of them gets called and the WebMethod doesn't get fired either. alert("1"); PageMethods.LoginUser(onSuccess, onFailure, email, pass); alert("2"); function onSuccess(val) { } function onFailure() { } [WebMethod(EnableSession = true)] public static int LoginUser(string email, string pass) { //Doesn't get...

Retrieve data from one table and insert into another table


sql,asp.net,sql-server
I am trying to retrieve data from one table and then insert it into another table. This is a a sample of the first table in which there is the following data. tb1 is the table which consists of data. The two columns Manager and TeamLeader basically means for example...

Problems With FOR XML AUTO


sql,asp.net,sql-server,subquery,sqlxml
i have the following Query: SELECT QuestionID_PK , QuestionTitle , ( SELECT dbo.Tags.TagID_PK , dbo.Tags.TagTitle , dbo.Tags.TagTitle_EN FROM dbo.Question_Tag_Rel INNER JOIN dbo.Questions ON dbo.Question_Tag_Rel.QuestionID_FK = dbo.Questions.QuestionID_PK INNER JOIN dbo.Tags ON dbo.Question_Tag_Rel.TagID_FK = dbo.Tags.TagID_PK AND dbo.Questions.QuestionID_PK = '2116' FOR XML PATH('') , TYPE , ELEMENTS ) AS Tags FROM Questions WHERE...

Make uneven table layout


html,asp.net
When I use <table> with <tr> and <td> I always get NxN tables and not what I want. For example: <table border = "1"> <tr> <td> Do you love peanuts? This is a very important question. </td> </tr> <tr> <td> Yes, I do. </td> <td> No, I don't. </td> </tr>...

Why is my View not displaying value of ViewBag?


c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor
I have a little blog application with posts and tags. This is my model for Post: namespace HelloWorld.Models { public class Post { [Required] [DataType(DataType.Text)] public string Title { get; set; } [Required] [DataType(DataType.MultilineText)] public string Description { get; set; } [Required] [DataType(DataType.DateTime)] public DateTime PostDate { get; set; }...

System.net.http.formatting causing issues with Newtonsoft.json


c#,asp.net,asp.net-mvc,json.net
My Windows service is in the same solution as a MVC project. The MVC project uses a reference to SignalR Client which requires Newtonsoft.Json v6 + the Windows service uses System.Net.Http.Formatting, which requires Newtonsoft.Json version 4.5.0.0. I assumed this would not be a problem, as I could just use a...

Callback on client does not get triggered with SignalR


javascript,c#,asp.net,signalr
I'm currently getting up to speed with SignalR, and tried to build a very basic message notification system using the very basic understanding of SignalR that I have but I can't get the messages to come back after the submission. I've read up on numerous blogs on the topic and...

Event on dynamically created checkbox asp.net


c#,jquery,asp.net,table,checkbox
I started to programming with asp.net, I have a table with some checkboxses. The problem is, I can't create static tables, because this action is linked with some parameters. Anyway.. When I click on the First checkbox I want to invert the other checkboxes in this table. How can i...

How IE setting affect authorization


asp.net,iis
I have a Webform app written in asp.net 4.5 and trying to understand how IE plays a role for authentication. So far my search has not provided a solid answer I know webconfig setting override iis setting. But assume we set the authorization mode to anonymous in both of iis...

Third-party security providers like Google, Twitter etc. in ASP.Net


asp.net,authentication
I have created a standard ASP.Net web project in Visual Studio 2013 and enabled authentication. A class called 'StartupAuth.cs' is created auotmatically, with following lines. When the app runs on localhost dev server it throws an exception as pasted in screen shot below the code. I need to have it...

RequiredFieldValidator not working in my ASp site


c#,css,asp.net,twitter-bootstrap
I'm trying to learn some C# & asp, while creating a booking page in Visual Studio. I have faced a little problem with the RequiredFieldValidator, because when i click the button, nothing happens. I'm using the bootstrap css files to make in a little more shiny. Some code of the...

Cant delete in database because of constraints


c#,sql,asp.net,oracle
I am making an asp.net project and I am trying to delete a row in my database but that table got constraints. I am using this method to delete it.How can I rewrite it so that all constraints are disabled or something in order that i can properly delete a...

Deserializing Json data to c# for use in GridView - Error Data source is an invalid type


c#,json,gridview,serialization,.net-4.5
I am relatively new to working with C# (v5.0) and Json data (Newtonsoft.Json v6.0) and am seeking assistance in resolving an error when attempting to populate a .Net 4.5 GridView control. My sample Json data as returned by a web service is: { PersonDetails: [ { Book: "10 ", FirstName:...

Select @field From table as parameter


asp.net,sql-server,parameter-passing
I have a database table with some columns like "col_a", "col_b" and I want to retrieve just one column of it. But the column is depended on some user selection. Some times could be the col_a, the col_b, c .... So my question is if I can select a field...

ASP.NET httpHandlers & handlers


asp.net,asp.net-mvc
I am confused about httpHandlers in system.web and handlers in system.webServer. What is the difference between these two configuration? And how and when to use them? Actually another question is for modules as well: httpModules in system.web and modules in system.webServer...

ASP.net website is not working properly while configuring in Internet Information Services


c#,asp.net,oracle11g,iis-7
I have created small webpage in ASP.net using c# in front end and oracle 11g at back end. Webpage is running successfully on my local pc as well as in windows server 2008 r/2 in visual studio 2010. So, i have configured same wabpage in IIS in server 2008 r/2...

Database object with different data


sql,asp.net,asp.net-mvc,database,entity-framework-6
I'm making a web page in ASP.NET MVC which compares prices from different shops. I have a one-to-many with products and the shops, where the SHOP has one PRODUCT and a PRODUCT has many SHOPs, the problem is that the product is the same but the price is different. Example:...

Can I uniquely identify 2 check boxes so that I can add a different image to each?


html,css,asp.net,checkbox
Currently I am using an image for checked and unchecked checkboxes the html and css is below. <div class="text-field-box text-field-box-mobile radio-button-box small"> <asp:CheckBox ID="ChkOffer1" text=" " runat="server" class="checkbox checkbox-mobile radio" Visible="true" EnableViewState="true"></asp:CheckBox> <% Response.Write(Session("Offer1"))%> </div> and css input[type=checkbox] { display:none; } input[type=checkbox] + label { background-image: url("checkbox-default.png"); background-repeat: no-repeat;...

check if file is image


c#,asp.net,asp.net-mvc
I want to check if file is image. and then you will see a link where you can see the image. But the link only has to appear if file is link. I try it like this: if (!String.IsNullOrEmpty(item.FileName)) { var file = item.FileName; string[] formats = new string[] {...

Convert Double from String


asp.net,vb.net,visual-studio-2012,converter
When converting string to floating, the converter creates wrong results. ?Global.System.Convert.ToDouble("635705821821928755").ToString("0") "635705821821929000" ?Global.System.Convert.ToSingle("635705821821928755").ToString("0") "635705800000000000" I am working with VB.Net Visual Studio 2012, Framework 4 on ASP.Net Webpage. Is there any solution for converting huge numbers from string into floating?...

Cannot start Website in IIS - W3SVC running


asp.net,iis
I am trying to start a Website in IIS but it doesn't get started and gives me following error: The World Wide Web Publishing Service (W3SVC) is stopped. Websites cannot be started unless the World Wide Web Publishing Service is running. How can I resolve it? I donot even know...

Blank screen on GridView


android,arrays,gridview
I'm trying to create a GridView with an array of strings. These are XML, and MainActivity and Adapter, but what I get is a blank screen. I'm change the background, but the result is the same, but clicking on a point on the screen appears to me the toast stating...

Sending LIst via ajax to complex model


javascript,c#,asp.net,ajax
I know I've done this before but I can't seem to get this to work. I have the following JavaScript; $("#btnTestVouchers").click(function () { var postData = { "workplaceGiverId": $(".wpgDropdownList").val(), "fromMemberId": $(".wpgFromMemberDropdownList").val(), "toMemberId": $(".wpgToMemberDropdownList").val(), "voucherExpiryDate": $("#expiryDatePicker").val(), "recipients": JSON.stringify("[{'firstname':'a','lastname':'b','email':'c','voucheramount':'d'}]") }; console.log(postData); $.ajax({ type: "POST", url:...

why does the compiler complain about missing ctor of WebSocketHandler?


asp.net
I'm trying to use websocket in my project. to do so, I installed the package Microsoft Asp.Net SignalR, which consists of WebSocketHandler abstract class. i defined a class inheriting WebSocketHandler, but then the compiler complains: 'Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler' does not contain a constructor that takes 0 arguments'. It seems wierd to me,...

Asp.Net Identity find users not in role


asp.net,linq,entity-framework,asp.net-identity
I need to find all users that DONT'T contain a certain role, using Asp.Net Identity. So far I have something like this but it is not working. (From role In context.Roles From userRoles In role.Users Join us In context.Users On us.Id Equals userRoles.UserId Where role.Name <> "SomeRole" Select us.UserName) This...

How to change the colour and style of MajorGrid of AxisY in ASP.net chart


c#,asp.net,charts
I made a chart in asp.net and I want to change the color of the MajorGrid to light grey and style to dash. Any suggestions?

Gridview items not populating correctly


asp.net,vb.net
I have data I am trying to input into a gridview. I am looking up the number of rows for the gridview and adding data into them like this: My "test" however does not get populated into the Submitted and Variance BoundFields in the Gridview. All that populates is the...

Unable to find the auto created Database


c#,asp.net,asp.net-mvc,entity-framework
I have created simple ASP.NET MVC4 application using EntityFramework Code first approach. The entity class is as below: public class Album { [Key] public int AblumId { get; set; } public decimal Price { get; set; } public string Title { get; set; } } public class MusicContext : DbContext...

How do ASP.NET Web APIs work once built with MSBUILD?


c#,asp.net,msbuild
I'm new to coding and spend most of my time in mobile application development with Phonegap, I've been learning how to code ASP.NET Web APIs and I know how it generally all works while having the code open in front of me but --- I was asked a question today...

Access manager information from Active Directory


c#,asp.net,active-directory
Attach is the picture of active directory, which i got from my IT department. Now i want to get the manager information in C#. NOTE: I am able to get all information of user but there isn't any key of manager, but IT department just gave me above attached...

Azure Mobile Services: migrate to non-Azure Windows Server


asp.net,azure,azure-mobile-services
I am planning to use Windows Azure Mobile Services for a new project. As far as I am concerned, Mobile Services are closely tied to Windows Azure. So far, I'm pretty happy with Windows Azure. What if, in the future, I decide to port the functionality to a non-Azure Windows...

Clear all selected items in a gridview


java,android,gridview,arraylist,expandablelistview
I have a gridview inside a ExpandableListView with CHOICE_MODE_MULTIPLE, I'm trying to deselect all items when I press a button, but the way I'm doing it it is only unselecting the last item, how can I clear all of them? @Override public int getCount() { return child.size(); } @Override public...

UpdatePanel AsyncPostbackTrigger not firing


asp.net,ajax,webforms,updatepanel
I've got a little problem, any help is appreciated. Situation looks like this: <asp:UpdatePanel ID="UP_Panel" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:DropDownList ID="ddlSwitch" runat="server" Width="250px" AutoPostback="true" OnSelectedIndexChanged="ddlSwitch_SelectedIndexChanged"> <asp:ListItem Value="continent" Text="Continent"></asp:ListItem> <asp:ListItem Value="region" Text="Region"></asp:ListItem> <asp:ListItem Value="country"...

Server side session in asp.net


asp.net,web-services,session
I want to set one value in server side session in client side and need to access that session in web service, so i tried below In client side : //Set the server side session like below var vr_="demo.png"; '<%Session["path"] = "' + vr_ + '"; %>'; //In alert,checked the...

add BR between text in dynamically created control


c#,asp.net
I've got a dynamically created List in asp.net with the following code: HtmlGenericControl li = new HtmlGenericControl("li"); li.ID = "liQuestions" + recordcount.ToString(); li.Attributes.Add("role", "Presentation"); ULRouting.Controls.Add(li); HtmlGenericControl anchor = new HtmlGenericControl("a"); li.Attributes.Add("myCustomIDAtribute", recordcount.ToString()); anchor.InnerText = "Test " + new HtmlGenericControl("br") + "12345"; li.Controls.Add(anchor); I tried to put in a HtmlGenericControl but...

Random Questions keep on repeating


c#,asp.net
I have made a system in visual studio using asp.net(c#) where the questions are taken from database and are displayed to users. but the questions are getting repeated and i can't figure about whats wrong with it and plus some questions are not getting displayed. below is the relevant C#...

.NET wep api won't accept %2E or . in api request uri


c#,jquery,asp.net,ajax,json
We're trying to create our first web api using the .net framework. To try this we've used this demo project: http://www.codeproject.com/Articles/549152/Introduction-to-ASP-NET-Web-API In this project we've changed the find() function of the AJAX script so it only sends one var to our new democontroller.: <script> var uri = 'api/Demo'; function find()...

How to format label in ASP.net chart control


c#,asp.net,asp.net-mvc,c#-4.0,reporting-services
I have created a column chart in asp.net. I am showing the date on x-axis. At the moment the date is shown as dd/mm/yyyy. All I need is to show the date as dd-mm-yy and ideally Weekday, dd-mm-yy e.g. Monday, 12-05-15. <asp:Chart ID="Chart1" runat="server" Height="400px" Width="900px" BorderWidth = "1"> <Series>...

SQL Server / C# : Filter for System.Date - results only entries at 00:00:00


c#,asp.net,sql-server,date,gridview-sorting
I have a connected SQL Server database in Visual Studio and am displaying its content in a grid. I created a dropdown menu with the column names as selectable options and a text field to filter for specific content, e.g., DropDown = "Start" - Textfield = 14.03.2015 = Filter Column...

asp.net background in 3 pieces to be stationary


html,css,asp.net
I am developing asp.net webforms with a background that is made up of 3 images; top, left and right. The 3 pieces are cropped from a full image to accomodate for content body of 770px width in the middle. At present, these 3 images moves with the body content as...

Difference between application and module pipelines in Nancy?


c#,asp.net,nancy
I have seen in the documentation of Nancy, sometimes these two are referred distinctively. And also is there a difference in the Before/After hooks of these two pipelines?...

Show/hide tinymce with radio buttons


c#,asp.net,asp.net-mvc,tinymce
I try to show/hide a tinymce with radobutton. Like yes/no. So there are two radio buttons. yes - will show the tiny mce and no will hide the tinymce. I have this: showing tiny mce: <div class="form-group"> @Html.Label(Resources.Entity.Product.PdfMessage, new { @class = "text-bold control-label col-md-2" }) <div class="col-lg-6 col-md-8 col-sm-10...

Catch concurrency exception in EF6 to change message to be more user friendly


c#,asp.net,.net,entity-framework,entity-framework-6
I am using EF6.1 and i would like to change the message to a more system specific message when the below exception is thrown. Store update, insert, or delete statement affected an unexpected number of rows (0) Now, my problem is i cannot seem to catch the exception? I have...

Multiple Posted Types asp.net 5 MVC 6 API


c#,asp.net,asp.net-mvc,asp.net-5,asp.net-mvc-6
I can use [FromBody] for single type , but is there any way to use multiple? From the searching and reading I've done there is not a way, but i don't know if a way has been added in MVC 6. If not, where would be best to start with...

Trigger a js function with parameter from code behind


c#,jquery,asp.net,scriptmanager,registerstartupscript
C# Trigger a js function with parameter from code behind. I have the following code: C#: ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptManager1", String.Format(@"ShowHideMessageBlock('{0}')", @"#successMsg"), true); js: function ShowHideMessageBlock(xid) { var c = xid; console.log(c); $(c).fadeIn('slow', function () { $(this).delay(5000).fadeOut('slow'); }); } When I open the console window I get the following message: Uncaught...

Creating a viewmodel on an existing project


c#,asp.net,asp.net-mvc
I am trying to add a viewmodel to a project because I want my view to use two separate models. I've looked at different tutorials trying to learn how to do this but I am having some trouble. Before, the view was strongly binded(typed?) to the Person model, but now...

CommandName = Insert in EditTemplate of ASP.NET ListView throws “Insert can only be called on an insert item”


c#,asp.net,listview
I am supporting a web application. In that, there are two tables - TaxCode and TaxRate. TaxCode has 1 to many relationship with TaxRate. The UI has a ListView with LayoutTemplate, ItemTemplate and EditTemplate to show TaxCode. When the users selects a tax code in EditTemplate it shows a CutomGridView...