Tuesday, February 19, 2008

Datagrid( with database retrieval ) as webpart sharepoint

I. Reference link
http://www.devx.com/dotnet/Article/26732/1954,
there u can download zip file and in that GetDataChildControl.cs
is taken and modified as follows

1. Use the STSDEV tool to creat a project.
2. Open the customwebpart1.cs and modify the page to look as follows:

using System.Data;
using System.Data.SqlClient;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;
using System.ComponentModel;

namespace DbGridWebPart
{
[DefaultProperty("Text"),
ToolboxData("<{0}:GetData runat=server>"),
XmlRoot(Namespace = "WebParts")]
public class CustomWebPart1 : WebPart
{
private const string defaultConnection = "Server=server;database=pubs;Integrated Security=false;User Id=sa;Password=";

private string connectionString = defaultConnection;

[Browsable(true),
Category("Data"),
DefaultValue(defaultConnection),
WebPartStorage(Storage.Shared),
FriendlyName("Connection String"),
Description("Connection String")]
public string ConnectionString
{
get
{
return connectionString;
}

set
{
connectionString = value;
}
}

private const string defaultSQL = "SELECT TOP 2 au_lname, au_fname FROM Authors";
private string sqlString = defaultSQL;

[Browsable(true),
Category("Data"),
DefaultValue(defaultSQL),
WebPartStorage(Storage.Shared),
FriendlyName("SQL Command"),
Description("The SQL command, or stored procedure to execute")]
public string SQLString
{
get
{
return sqlString;
}
set
{
sqlString = value;
}
}
///
/// Constructor for GetDataChildControl
///

public CustomWebPart1()
{
try
{
}
catch (Exception excpt)
{
Label lbl = new Label();
lbl.Text = "An error occured : " + excpt.ToString();
Controls.Add(lbl);
}
}
private bool bDGAdded = false;
///
/// Render this Web Part to the output parameter specified.
///

/// The HTML writer to write out to
protected override void RenderWebPart(HtmlTextWriter output)
{
// If the data grid has not been added
if (!bDGAdded) AddDG();

base.RenderWebPart(output);
}

protected void AddDG()
{
System.Data.SqlClient.SqlConnection mySQLConnect = new SqlConnection(connectionString);

mySQLConnect.Open();

SqlCommand myCmd = new SqlCommand(sqlString, mySQLConnect);

System.Data.SqlClient.SqlDataAdapter myAdapter = new SqlDataAdapter(myCmd);
DataSet ds = new DataSet();

myAdapter.Fill(ds, "Test");

DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
Controls.Add(dg);
bDGAdded = true;
}
}
}


3. Then the rest are same as deployment to the server.

4. And if u want to change the query or server settings in sharepoint site, click the modify shared web part on the webpart menu and then point to Data setttings, there u can change those settings.



  

No comments: