Category Archives: DataSet

ASp.Net 2.0 GridView Delete Button Confirmation pop-up

While using GridView in asp.net pages wants to confirm the deletion form user. To do this we can take him to another page having GUI to confirm and then delete the record on that page.

Instead of doing so much hardwork you can achieve this on the same page with a little bit of extra code.

Workaround

Add a client alert script to the delete button of every row.
In the delete event of GridView delete the record.

Code

==================================================
Page’s Aspx Design File Begins
==================================================
<asp:GridView ID=”gvFaq” runat=”server” AutoGenerateColumns=”False” CellPadding=”4″
ForeColor=”#333333″ GridLines=”None” OnRowDataBound=”gvFaq_RowDataBound” OnRowDeleting=”gvFaq_RowDeleting”>
<FooterStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<RowStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ />
<Columns>
<asp:BoundField DataField=”slno” HeaderText=”Sl No.” />
<asp:BoundField DataField=”cHeading” HeaderText=”Question” />
<asp:BoundField DataField=”cPosition” HeaderText=”Position” />
<asp:CommandField HeaderText=”Manage” ShowSelectButton=”True” />
<asp:CommandField HeaderText=”Delete” ShowDeleteButton=”True” />
</Columns>
<PagerStyle BackColor=”#284775″ ForeColor=”White” HorizontalAlign=”Center” />
<SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ />
<HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<EditRowStyle BackColor=”#999999″ />
<AlternatingRowStyle BackColor=”White” ForeColor=”#284775″ />
</asp:GridView>
==================================================
Page’s Aspx Design File Ends
==================================================

Database Design FIle

==================================================
Code Behind File Begins
==================================================
1) Import Namespaces
using System.Data.SqlClient;

2) Declare global variables which will be used in page
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlConnection myConnection;
String connStr = “your database connection string goes here”‘;
String sql = string.Empty;

3) Page Load event
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
fillGridView();
}
}

4) GridView filling method
private void fillGridView()
{

try
{
myConnection = new SqlConnection(connStr);
sql = “select * from tblFaq order by slno desc”;

da = new SqlDataAdapter(sql, myConnection);
ds.Clear();
da.Fill(ds, “tblFaq”);

gvFaq.DataSource = ds.Tables[0];
Page.DataBind();

}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

5) In the RowDataBound event add a java script event to the delete cell.
protected void gvFaq_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[4].Attributes.Add(“onClick”, “return confirm(‘Are you sure you want to delete the record?’);”);
}
}

6) Handle the RowDeleting event to delete the record of current row.

protected void gvFaq_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
myConnection = new SqlConnection(connStr);
myConnection.Open();
sql = “delete from tblFaq where slno = ” + Convert.ToInt32(gvFaq.Rows[e.RowIndex].Cells[0].Text);
SqlCommand oldcom = new SqlCommand(sql, myConnection);
oldcom.ExecuteNonQuery();
myConnection.Close();
fillGridView();
Response.Write(“Record Deleted”);
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}

==================================================
Code Behind File Ends
==================================================
The output will look like this

For Source Code visit http://dotnetcoderoom.blogspot.com/2008/08/aspnet-20-gridview-delete-button.html


XML Serialization in .Net Framework (Write Xml from Dataset)

WHAT IS SERIALIZATION ?
Serialization is converting an object to a format in which it can be saved (exported) as file or a physical medium. A simple and basic example would be, if we create an XML from a Dataset it is called Serialization.

CODE:
try
{
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlConnection myConnection;
String connStr = ConfigurationManager.ConnectionStrings[“DatabaseConnectionString1”].ToString();

SqlConnection myConnection = new SqlConnection(connStr);
String sql = “select * from tblCategory”;
da = new SqlDataAdapter(sql, myConnection);
ds.Clear();
da.Fill(ds, “tblCategory”);
ds.WriteXml(Server.MapPath(“~/xmls/info.xml”));
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

The above code will write an XML file called info.xml from a Dataset called “ds” into xmls folder in root of website.

Options
Alternatively we can use some advanced options to format the data which is being written.

ds.WriteXml(Server.MapPath(“~/xmls/info.xml”, XmlWriteMode.WriteSchema);

Some options are. Some of the attributes available in Microsoft .Net Framework are as follows:

XmlWriteMode.DiffGram — Writes the entire DataSet as a DiffGram.
XmlWriteMode.IgnoreSchema — Writes the current contents of the DataSet as XML data, without an XML Schema Definition language (XSD) schema.
XmlWriteMode.WriteSchema — Writes the current contents of the DataSet as XML data with the relational structure as inline XSD schema.
For more articles updates and sourcecodes please visit dotnetcoderoom


Update Dataset data back to Database

This post explains how to insert, update, and delete data in a Database using Dataset.

The DataSet can be considered an in-memory cache of data retrieved from a database. The DataSet consists of a collection of tables, relationships, and constraints.

Firstly, we have to fill data into a DataSet from Database.
Secondly, when the DataSet is loaded, you can modify the data, and the DataSet will keep track of the changes made bu user.

The Add method of DataTable accepts either an array of the expected data columns, or a DataRow.

(Please note that all code is in c# language)

Step 1: Create a new Connection and SqlDataAdapter
SqlConnection myConnection = new SqlConnection(“connectionStringGoesHere”);
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(“Select * from tblNews”, myConnection);
DataSet myDataSet = new DataSet();
DataRow myDataRow;

Step 2: Create SqlCommandBuilder(The SqlDataAdapter does not automatically generate the Transact-SQL statements required to match changes made to a DataSet with SQL Server. But, you can create a SqlCommandBuilder object to automatically generate Transact-SQL statements for single-table updates.)
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);

// Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary
// key & unique key information to be retrieved unless AddWithKey is specified.
mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

mySqlDataAdapter.Fill(myDataSet, “tblNews”);

Step 3: Add rows to DataTable

myDataRow = myDataSet.Tables[“tblNews”].NewRow();
myDataRow[“cNewsId”] = “NewID”;
myDataRow[“cHeading”] = “New Heading”;
myDataRow[“cContent”] = “Content here”;

myDataSet.Tables[“tblNews”].Rows.Add(myDataRow);

Step 4: Editing Row Data
We can change the data in a DataRow by accessing the DataRow. Use the index of the row in the RowsCollection accessed through the Rows property:

myDataSet.Tables[“tblNews”].Rows[0][“cHeading”]=”Abc”;

Access a specific row by specifying the Primary Key value:

DataRow myDataRow1 = myDataSet.Tables[“tblNews”].Rows.Find(“124”);
myDataRow1[“cHeading”]=”Abc”;

Here “124” is the value of the Primary Key “cHeading” in the “tblNews” table.

Step 5: Deleting a record
Use Delete method to delete a Row. All changes are done in dataset until you don’t explicitly update DataSet data to the Database. Use RejectChanges method of DataSet to reverse all changes made to DataSet.

myDataSet.Tables[“tblNews”].Rows[0].Delete();

Note: The original and new values are maintained in the row. The RowChanging event allows you to access both original and new values to decide whether you want the edit to proceed.

SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);

Step 6: Finally Update DataBase
To submit the data from the DataSet into the database, use dataAdapter’s Update method.

mySqlDataAdapter.Update(myDataSet, “tblNews”);

A Visual Studio Solution code sample will be coming soon……

**End of article**

For more articles updates and sourcecodes please visit dotnetcoderoom