Wednesday, May 20, 2009

Creating and Reading XML through ADO.Net...

Objective:
1: Creating one XML file taking data from my table
2: Reading that XML file to a gridview.
Design of form.


//Method for showing record in first grid view at the time of page_load.....
public void show_data()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=susant\\SQLEXPRESS; Integrated Security=True; Database=Infitech";
try
{
con.Open();
string str1 = "select * from student";
SqlDataAdapter da1 = new SqlDataAdapter(str1, con);
DataSet ds1 = new DataSet();
da1.Fill(ds1, "temp");
GridView1.DataSource = ds1.Tables[0];
GridView1.DataBind();
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}

protected void Page_Load(object sender, EventArgs e)
{
//to show all the records present in table
show_data();
}

//button for creating the XML file...

protected void btnCreate_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=susant\\SQLEXPRESS; Integrated Security=True; Database=Infitech";
try
{
con.Open();
string str2 = "select * from student";
SqlDataAdapter da2 = new SqlDataAdapter(str2, con);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "temp");
//It will create one XML file in C:\MyXML.xml..
ds2.WriteXml("C:\\MyXML.xml");
Response.Write("Xml file created successfully...!!!");
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}

//Button for reading the XML file and showing in gridview2...

protected void btnRead_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=susant\\SQLEXPRESS; Integrated Security=True; Database=Infitech";
try
{
con.Open();
string str3 = "select * from student";
SqlDataAdapter da3 = new SqlDataAdapter(str3, con);
DataSet ds3 = new DataSet();
da3.Fill(ds3, "temp");
//It will create one XML file in C:\MyXML.xml..
ds3.ReadXml("C:\\MyXML.xml");
GridView2.DataSource = ds3.Tables[0];
GridView2.DataBind();
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
Bookmark and Share