Formatting Chemical Formulae in DataGrid


Introduction:

In this article we'll see how to format chemical formulae in DataGrid Web Server Control. In short display the chemical formulae stored in the database as CO2 to CO2 on the Webform.

The Database Data is stored as:



To begin with User Interface Drag and drop

  • DataGrid

<asp:DataGrid id="DataGrid1" AutogenerateColumns="false" runat="server">
<
Columns>
<
asp:TemplateColumn HeaderText ="Chemical Formula">
<
ItemTemplate>
<
font face=Arial size=3 >
<
b>
<%#GetProperFormat(DataBinder.Eval(Container.DataItem,"Formula").ToString())%>
</b>
</
font>
</
ItemTemplate>
</
asp:TemplateColumn>
</
Columns>
</
asp:DataGrid>

Now our code. :

  • Method BindData : To Populate the DataSet and assign the value to relevant control
  • Function GetProperFormat : To Format Chemical Formula as H2O(storedin database) to H2O(on the WebForm).

C#

private
void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
BindData ();
}
}
DataSet ds =
new DataSet ();
void BindData()
{
string sqlStmt = "Select * from ChemicalFormula ";
string conString = "server=localhost;database=Northwind;uid=sa;pwd=;";
SqlDataAdapter myda =
new SqlDataAdapter(sqlStmt, conString);
myda.Fill(ds);
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
protected string GetProperFormat(string fldval)
{
string strval="" ;
//Navigate through every character of the fldval
for(int i = 0;i< fldval.Length ;i++)
{
//Check for IF the value is numeric True/False
if(Char.IsNumber (fldval[i] ))
{
strval = strval + "<sub>" + fldval[i] + "</sub>";
}
else
{
strval = strval + fldval[i];
}
}
return strval;


VB.NET

Private ds As DataSet = New DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load()
'Put user code to initialize the page here
If Not Page.IsPostBack Then
binddata()
End If
End
Sub
Sub
binddata()
Dim sqlStmt As String = "Select * from ChemicalFormula "
Dim conString As String = "server=localhost;database=Northwind;uid=sa;pwd=;"
Dim myda As SqlDataAdapter = New SqlDataAdapter(sqlStmt, conString)
myda.Fill(ds)
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub
Function
GetProperFormat(ByVal fldval As String)
Dim FieldsValues() As String = Regex.Split(fldval, "")
Dim i As Integer
Dim strval As String
'Navigate through every character of the FieldValue
For i = 0 To FieldsValues.Length - 1
'Check for IF the value is numeric True/False
If IsNumeric(FieldsValues(i)) Then
strval = strval & "<sub>" & FieldsValues(i) & "</sub>"
Else
strval = strval & FieldsValues(i)
End If
Next
Return strval
End Function

The Output of this code:


Similar Articles