Editing a table in a database via a datagrid

I want a dataset where I can click Edit ("Editera" in Swedish) and edit
the selected post in the database. But with the .aspx-file and its
codebehind-file below, when I click "Editera" the dataset disappears
from the page.


namespace mysite
{
  using System;
  using System.Collections;
  using System.ComponentModel;
  using System.Data;
  using System.Data.SqlClient;
  using System.Web;
  using System.Web.SessionState;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.Security;
  using System.Configuration;

  public class errors : System.Web.UI.Page
  {
      public System.Web.UI.WebControls.DataGrid MyDataGrid;
      public System.Web.UI.WebControls.RequiredFieldValidator errorReqVal;
      public System.Web.UI.WebControls.Label Message;
      public System.Web.UI.WebControls.TextBox error;

      public System.Web.UI.WebControls.Label Label1;
      public System.Web.UI.WebControls.RequiredFieldValidator edit_errorReqVal;
      public System.Web.UI.WebControls.TextBox edit_error;

    SqlConnection myConnection;

    protected void Page_Load(Object Src, EventArgs E)
    {
        myConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);

        if (!IsPostBack)
        {
            BindGrid();
            Page.DataBind();
        }
    }

    public void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E)
    {
        MyDataGrid.EditItemIndex = (int)E.Item.ItemIndex;
        BindGrid();
    }

    public void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs E)
    {
        MyDataGrid.EditItemIndex = -1;
        BindGrid();
    }

      public void MyDataGrid_Update(Object sender, DataGridCommandEventArgs E)
      {
          if (Page.IsValid)
          {
                string updateCmd = "UPDATE Feltexter SET FelText = '@FelText' WHERE FelAnvID = @AnvID";
                SqlCommand cmd = new SqlCommand(updateCmd, myConnection);

                cmd.Parameters.Add("@FelText", SqlDbType.NVarChar, 40).Value = edit_error.Text;
                cmd.Parameters.Add("@AnvID", SqlDbType.Int, 10).Value = Session["UserID"];

                cmd.Connection.Open();

              cmd.ExecuteNonQuery();
              MyDataGrid.EditItemIndex = -1;


              cmd.Connection.Close();

              BindGrid();
          }
          else
          {
          }
      }

    public void AddError_Click(Object sender, EventArgs E)
    {
        if (Page.IsValid)
        {

            String insertCmd = "insert into Feltexter (FelText, FelAnvID) values (@FelText, @FelAnvID)";

            SqlCommand myCommand = new SqlCommand(insertCmd, myConnection);

            myCommand.Parameters.Add(new SqlParameter("@FelText", SqlDbType.NVarChar, 300));
            myCommand.Parameters["@FelText"].Value = error.Text;

            myCommand.Parameters.Add("@FelAnvID", SqlDbType.Int, 400);
            myCommand.Parameters["@FelAnvID"].Value = Session["UserID"];

            myCommand.Connection.Open();

            try
            {
                myCommand.ExecuteNonQuery();
                Message.Text = "<b>Ditt felmeddelande har lagts till.</b>";
            }
            catch (SqlException e)
            {
                if (e.Number == 2627)
                    Message.Text = "Fel: En post med samma primärnyckel existerar redan.";
                else
                    Message.Text = "Fel: Fältet kunde inte läggas till. : " + e.Message;
              Message.Style["color"] = "red";
            }

            myCommand.Connection.Close();
        }

        BindGrid();
    }

    public void BindGrid()
    {
        SqlDataAdapter myCommand = new SqlDataAdapter("select * from Feltexter where FelAnvID = "+Session["UserID"]+"", myConnection);

        DataSet ds = new DataSet();
        myCommand.Fill(ds, "Feltexter");

        MyDataGrid.DataSource=ds.Tables["Feltexter"].DefaultView;
        MyDataGrid.DataBind();
    }

  }
}





          <ASP:DataGrid id="MyDataGrid" runat="server"
            Width="700"
            BackColor="#ccccff"
            BorderColor="black"
            ShowFooter="false"
            CellPadding=3
            CellSpacing="0"
            Font-Name="Verdana"
            Font-Size="8pt"
            HeaderStyle-BackColor="#aaaadd"
            EnableViewState="false">
          <Columns>
            <ASP:EditCommandColumn EditText="Editera" CancelText="Avbryt" UpdateText="Uppdatera" HeaderStyle-Wrap=false />
            <ASP:BoundColumn HeaderText="Felbeskrivning" DataField="FelText" />
        
         <asp:TemplateColumn HeaderText="Felbeskrivning" SortExpression="au_lname">
          <ItemTemplate>
            <asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "FelText") %>'/>
          </ItemTemplate>
          <EditItemTemplate>
            <nobr>
            <asp:TextBox runat="server" id="edit_error" Text='<%# DataBinder.Eval(Container.DataItem, "FelText") %>'/>
            <asp:RequiredFieldValidator id="edit_errorReqVal"
                ControlToValidate="error"
                Display="Dynamic"
                Font-Name="Verdana" Font-Size="12"
                runat=server>
            </asp:RequiredFieldValidator>
          </EditItemTemplate>
        </asp:TemplateColumn>      
          </Columns>  
          </ASP:DataGrid>


0
trexter
12/20/2005 7:11:14 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

2 Replies
405 Views

Similar Articles

[PageSpeed] 9

Can you post your BindGrid method, from the code you posted, it is not very clear how are you binding the dataset to the grid.

0
codeasp
12/20/2005 7:51:08 PM
can you repost this by copying your code into notepad or something so it's easier to read?
My Regards to All,
Jason -- O-H-I-O Go Buckeyes! #1
--- LIVESTRONG.ORG --- Please support the battle against cancer!
0
onewisehobbit
12/20/2005 7:51:32 PM
Reply:

Similar Artilces:

How to add the data present in the controls to a table control without any database involvement.
Hi All,i am four controls where i will write the text and once i click the add button those should get added to the table .i want 6 columns fixed in the table and rows as many as required.i tried doing that taking a table server control and able to load the table.but the problem is whenver i am adding a new row the old one is gfetting overwritten by this and at the end i am getting only one row.  System.Web.UI.WebControls.Table t1 = new System.Web.UI.WebControls.Table();  i have declared the below one global TableRow tr; TableCell tc1; TableCell tc2; TableCell tc...

displaying, Adding/editing database WithOUT a Datagrid/datalist control?! help please!
Hi, so far what i've seen of ASP.NET and databases is that its all to do with datagrids?! Now i don't know about you, but in regular ASP, i've never janked a bunch of records out of a database in order to just "simply" display them in a table fashion. For me it's mostly been getting 1 or more records and displaying the recordset in a form that is NOT a table.. So when i decided to make a switch from ASP to ASP.NET and i couldn't really find anything to clearly tell me how to do stuff i did before i got confused. What i'd want to do for example is to have an asp.net page...

Why I cannot create/edit tables in VS.Net Server explorer for SQL Server 2000 Developer local database?
I found that when I install MSDE, then I can create/edit database objects for MSDE database in Visual Studio 2003 Server Explorer, but when I try to create/edit database objects under the default database created by the SQL Server 2000 installation, I cannot do these tasks as no option for these tasks appear when I right-click on the database object in Server Explorer.  Anyone knows why this is happening?sun21170 I reproed your issue. And I found in MSDN it is said the Server Explorer can: -Open and view Server Explorer -Add a data connection -Add a server -Drag a...

masterpage and control formatting (table control, HTML table control)
I have a master page that contains 1 contentplaceholder.  In my default.aspx (that uses the masterpage layout) I have a table server control.  During page_load I get the data I need and repeatedly add the usercontrol to the table control, one user control per row.  My user control is basically a HTML table with several rows and columns that's populated with data upon creation. I want this table to fill the contentplaceholder's width. In addition within the masterpage I have a CSS link for my stylesheet. Here are my questions: Is there a better way of adding ...

How to place a DataGrid Control with in a DataGrid Control
Hi, I want to place a DataGrid control in a DataGrid control can any one plz tell me the procedure to place the control Thanks in Advance Krisamigo <!---<asp:DataGrid ID=dg_List runat=server><Columns><asp:TemplateColumn><ItemTemplate><asp:DataGrid ID=dg_List2 Runat=server></asp:DataGrid> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid> ---> Hardik Joshi...

Can I use a single database both for the tables created automatically for Login Control and my own tables
Can I have a single database containing both set of tables i.e. Tables, stored procedures created automatically after configuring  ASP.Net Configuration My own tables Because I want to authenticate the users through Login Controls, but also want to fetch data from my own tables. How should i Configure the web.config file to make a connection to the database before the user is authenticated. How should I access the connection string so that I can fetch the data and display it on the same page where the Login Control has been placed.Akber Ali Using a single database is no differe...

Editable table or a datagrid
Hi All, I am trying to do the following. I have to create a table that will accept user input (something like start date, time and end date time). I intend to bind the date cells with the calender object and the time cells to a drop down list for hours and minutes. The entered data is to be then saved in a database. Can anyone suggest whats the best approach to accomplish this: using tables or datagrid?? Regards Ankur I would use a datagrid since the edit portion of the datagrid is so easy to use.  If you need help w/the datagrid (setting it up or any portion of the cod...

can we find control of itemtemplate in updatecommandeventargs of datagrid after clicking edit button in the datagrid?
hi im having a editable datagrid here in one column of template field im having a label control in itemtemplate and a textbox control in edititemtemplate.now i want to find the label control in update command eventargs ...is this possible here im able to find the control of edititemplate but im unable to find the control of itemplate .pavankumar In any event, you can find controls in itemtemplate. for(int vLoop=0 ; vLoop<gv1.rows.count ; vLoop++) {     Label lbl = (Label)gv1.rows[vLoop].findcontrol("lblID"); }Give a man a fish and you feed him for a day. Te...

Editing Database from DataGrid
I have a datagrid that view data from my Access database with EDIT, UPDATE and CANCEL. I'm having problem to edit and update the database from datagrid, thou i can view all the data in the database. Please could anybody help me out, i use WebMatrix. Thanks Danieldanielnikky could you be more specific? post some code? Thanks for your reply, below is my code and the error messages. Thanks for your prompt help. Daniel   ' Insert page code here'    Function ViewClients() As System.Data.DataSet        Dim connectionString As Strin...

Tables and Datagrid control
Hello! How can I place a data grid control inside of table cell, so when the datagrid gets populated, the table (or cell) can expand itself and that it can be the same lenght that the datagrid is. Thank you, EduardoThanks,Please Mark this post as answered if it was helpful. Is this what you mean?<table style="width: 50%; height:auto">            <tr>                <td style="width: 100%; >     &n...

using javascript getting value from textbox when edit button is clicked and both controls are present in gridview control
Hi All using javascript I want to get value  from textbox when edit button is clicked and both controls that is texbox and button are present in gridview control .Alok Hi aloksinha83, Please see this post: http://forums.asp.net/t/1069245.aspx Thanks,Qin Dian TangMicrosoft Online Community SupportPlease remember to mark the replies as answers if they help and unmark them if they provide no help....

Data presentation control in another Data presentation control
 Hello,I want to make a menu with datalist or gridview control.Basically,the menu will be like this,Categories     Sub Categories.For example, for COMPUTING category there will be NOTEBOOKS DESKTOPS etc.There will be a image for CATEGORIES and linkbuttons with Subcategories.If I put a datalist inside a datalist and a link button inside the second datalist visually it satisfies my need.However,CommandArguments come from database to linkbutton.Andwhen one of these command buttons is cliked it must go to proper page.I dont know how to wrie an event_handler ,specifically, for...

Datagrid(.net 1.1) to GridView(.net 2.0) and using the RowUpdating event how to extract the values from the controls.
Ok  This is the settings: I use a Viewgrid with only itemtemplate colums for example. <asp:TemplateField HeaderText="Test"><ItemTemplate><asp:Label id="LBL_Test" text='<%# DataBinder.Eval(Container.DataItem, "Test1") %>' runat="server" meta:resourcekey="LBL_TestResource1"></asp:Label></font></ItemTemplate> <EditItemTemplate><asp:TextBox ID="HDN_Test" Text='<%# DataBinder.Eval(Container.DataItem, "Test1") %>' Runat="server" meta:resourcekey="HDN_TestResource1" /></EditItemTemplate></asp:TemplateField>  The ...

IWDBEdit control set to IWDBGridColumn.Control not editable [Edit]
Hi folks. I'm relatively new to IntraWeb and am having trouble with my application. It is a simple app that is supposed to show a list of user accounts in a grid and allow the user to edit data in the accounts. I have a TADOQuery connecting to MS SQL, with 'Select * from UserAccounts' as the sql text. I have a TDataSource with the Dataset property pointing to my TADOQuery object. Both of these objects exist as part of the UserSession. On my main form, I have an IWDBGrid, IWDBNavigator, and an IWDBEdit control. They are all hooked up to the TDatasource in the UserSessi...

Web resources about - Editing a table in a database via a datagrid - asp.net.presentation-controls

Database - Wikipedia, the free encyclopedia
... requiring information. For example, modelling the availability of rooms in hotels in a way that supports finding a hotel with vacancies. Database ...

Database - Wikipedia, the free encyclopedia
A database is an organized collection of data . The data are typically organized to model aspects of reality in a way that supports processes ...

Five million customers affected by Vtech database hack
Toy and educational material seller Vtech has revealed five million customers were affected by a hack of its app database and has also suspended ...

Donald Trump wants "surveillance of certain mosques," database of refugees - Videos - CBS News
... rally in Birmingham, Alabama, Republican presidential candidate Donald Trump called for increased scrutiny over mosques, along with a database ...

IDG Contributor Network: Avoiding ginormous transaction logs with SharePoint databases
... why do we see these humongous transaction logs so often? I am going to blame it on a “misunderstanding” of how Microsoft describes a full database ...

Trump Wants A Database For All Syrian Refugees Who Enter America
Trump Wants A Database For All Syrian Refugees Who Enter America

Change your passwords: NexusMods suffers database breach
... security breach by posts on reddit. Cybersecurity firm REN-ISAC had apparently contacted several university IT departments about a database ...

VTech Admits Lack of Database Security Opened Door to Hack
A SQL injection, a common software flaw, was found to be the root cause in the VTech breach.

MapR And Big Data In The World's Largest Biometric Database Project
India?s Aadhaar project is one of the world?s most ambitious big data projects, aiming to collect, store, and utilize biometric information from ...

Trump calls for surveillance of some mosques, attempts to clarify remarks on Syrian database
Trump calls for surveillance of some mosques, attempts to clarify remarks on Syrian database

Resources last updated: 12/11/2015 2:16:21 PM