Showing posts with label newbie. Show all posts
Showing posts with label newbie. Show all posts

Wednesday, March 28, 2012

substitute data from database into web form

Hello.

Newbie here, I have a field in a database called status with the values "I" or "A". I need to display "Inactive" or "Active" in a gridview or formview web page. How do I substitute these values.

Thanks in advance.

Is this data being displayed in a datalist / datagrid? You can either create a temp table in your sql or modify your code. If you post your code I can show you how, otherwise you can do something like this in your sql:

create table #temp(
activeInactiveField1 char(5)
, activeInactiveField2 char(10)
-- , your other fields here
)

Insert into #Temp(
-- all fields from your existing sql
from all your existing tables

update #temp
set activeInactiveField2 = 'Active'
where activeInactiveField1 = 'A'

update #temp
setActiveInactiveField2 = 'Inactive'
where activeInactiveField1 = 'I'

select * from #Temp
drop table #Temp

Then you can databind the field in your webform to activeInactiveField2


Hello, Thank you for the quick response. Below is my code. As stated I am a newbie and the filed I am working with is status. Thanks a lot.

<%@.PageLanguage="VB"AutoEventWireup="false"CodeFile="Default2.aspx.vb"Inherits="Default2" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Untitled Page</title>

</head>

<body>

<formid="form1"runat="server">

<div>

<asp:GridViewID="GridView1"runat="server"AutoGenerateColumns="False"DataSourceID="SqlDataSource1"

Style="z-index: 100; left: 0px; position: absolute; top: 0px">

<Columns>

<asp:BoundFieldDataField="Citation"HeaderText="Citation"SortExpression="Citation"/>

<asp:BoundFieldDataField="Type"HeaderText="Type"SortExpression="Type"/>

<asp:BoundFieldDataField="Status"HeaderText="Status"SortExpression="Status"/>

<asp:BoundFieldDataField="Last Name"HeaderText="Last Name"SortExpression="Last Name"/>

<asp:BoundFieldDataField="First Name"HeaderText="First Name"SortExpression="First Name"/>

<asp:BoundFieldDataField="Middle"HeaderText="Middle"SortExpression="Middle"/>

<asp:BoundFieldDataField="DOB"HeaderText="DOB"SortExpression="DOB"/>

<asp:BoundFieldDataField="Violation Date"HeaderText="Violation Date"SortExpression="Violation Date"/>

<asp:BoundFieldDataField="Charge"HeaderText="Charge"SortExpression="Charge"/>

<asp:BoundFieldDataField="Description"HeaderText="Description"SortExpression="Description"/>

<asp:BoundFieldDataField="Disposition"HeaderText="Disposition"SortExpression="Disposition"/>

<asp:BoundFieldDataField="Cost"HeaderText="Cost"SortExpression="Cost"/>

<asp:BoundFieldDataField="Paid"HeaderText="Paid"SortExpression="Paid"/>

<asp:BoundFieldDataField="Balance"HeaderText="Balance"SortExpression="Balance"/>

</Columns>

</asp:GridView>

<asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="<%$ ConnectionStrings:MUNI_COURTConnectionString4 %>"

ProviderName="<%$ ConnectionStrings:MUNI_COURTConnectionString4.ProviderName %>"

SelectCommand="SELECT * FROM [MUNI_COURT_REC]"></asp:SqlDataSource>

</div>

</form>

</body>

</html>


You can handle this in RowDataBound event of the gridview. To add this event to your gridview, when in design view of Visual Studio, click on gridview once to get the properties window. From that, go to the events window (identified by a small "lightning" icon) and look for RowDataBound event. Double click on this event and an event hadler will created in your code file. Just copy and paste this code there.

protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e) {if (e.Row.RowType == DataControlRowType.DataRow) {if(e.Row.Cells[7].Text =="A") { e.Row.Cells[7].Text ="Active"; }else { e.Row.Cells[7].Text ="Inactive"; } } }

Or you can change your select statement - something like select case status when 'i' then 'inactive' else 'active' end as status from blah blah blah...

By the way, it's never good practice to do a select *.


Hi, try this inline IIF statement to evaulate the status field and display conditional text. You will have to first convert your GridView to a template so you have control over the HTML controls.

<asp:LabelID="LabelStatus"runat="server"Text='<%# IIF(CONVERT.ToString(Eval("Status"))="A","Active", "Inactive") %>'></asp:Label>


Thanks I got that suggestion to work in a gridview and formview. Big Smile

What if I had another field called type that I had to change

"H" to "Harbor"

"C" to "Civil"

"T" to "Traffic"

"L" to "Local"


You can use the same solutions that are marked as answer to extend the functionality. Like in mine, you can access the columns by their index (0 based). So whatever the index of your "Type" column, access it in RowDataBound event, check the text of the cell, and change it accordigly.


Sorry bullpit,

when I run your suggestion I get the following error message

Compiler Error Message:BC30205: End of statement expected.

I believe your suggestion would work best.

I forgot to uncheck the answer message button


Paste your code here. Please use the InsertCode option in the text editor.


Partial Class Default2 Inherits System.Web.UI.Page Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBoundprotected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e) {if (e.Row.RowType == DataControlRowType.DataRow) {if(e.Row.Cells[7].Text =="A") { e.Row.Cells[7].Text ="Active"; } Else { e.Row.Cells[7].Text ="Inactive"; } } } End SubEnd Class

Thanks


learn_asp_fast:

Partial Class Default2 Inherits System.Web.UI.Page Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBoundprotected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e) {if (e.Row.RowType == DataControlRowType.DataRow) {if(e.Row.Cells[7].Text =="A") { e.Row.Cells[7].Text ="Active"; } Else { e.Row.Cells[7].Text ="Inactive"; } } } End SubEnd Class

The piece of code I posted was an event handler for RowDataBound event. An event handler is a method (function) by itself. What you did was that you attached an event handler the way I mentioned (by double clicking the RowDataBound event in designer) but also copied and pasted the event handler that I posted into the event handler that the designer generated. So now you have a function defined in another function, which is not right. Morover, you are using VB and the code I pasted was C#. Change the above code to this:

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBoundIf e.Row.RowType = DataControlRowType.DataRowThen If e.Row.Cells(7).Text ="A"Then e.Row.Cells(7).Text ="Active"Else e.Row.Cells(7).Text ="Inactive"End If End If End Sub

Bullpit,

Thank you very much for your time. I did realize I pasted the code into another function, but neith er way worked for me. I should be able to get this sample to work in other ways for me.

This a very helpful board.


Also, change the column index (7 in the code I posted) to the column index where you want to change the text. That might be the problem. For example, in your gridview, the "STATUS" colum index maybe 4 instead of 7.


Bullpit,

If you do not mind hopw do I get that to work in a Formview?

Thanks in advance

such a newbie that i cant even stand myself

so... here i am, 5 years of php/mysql programming and i feel like i'm learning from scratch... if anyone out there has a kind heart and a lot of patience... i reallly could use some help!

i'm to build an application in asp.net using SQL server db and have chosen c# style of programming as i am far better equipped to learn that syntax.

basically the only thing i have been able to do successfully is print the current time on the screen. i'm at quite a loss as to where to start...

the 1st issue is with the Web.config file -- I got it to show the error messages on the page but only if there is no other code but this: <customErrors mode="Off" />

once i add in <authentication mode="Forms" /> it makes the page act just like it did w/out the customErrors code giving me the whole runtime error msg telling me about customErrors"Details: To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors..."

I think the real problems is- I don't even know where to start or the why's and what's... I have done some basic forms in asp but that isn't much like .net at all. Ican't even seem to get going since everything i try is giving me that Runtime Error message.. Even the full zipped up mini apps that i downloaded that are all ready to go give me errors.

Here are some of my more ignorant questions...

1. I'm using Dreamweaver to develop with. Would it be better to use Visual Web Developer? Would the time spent learning that new interface be made up for since it's built specifically w/ asp.net. I'm not a super dreamweaver developer anyway- i have always hand coded using Homesite but my current job wants me in dreamweaver so... Of course the visual web dev. express i downloaded - I can't even figure out how to change the defaultPageLanguage="VB" to be C#.

2. does anyone know of any sort of quick-start guide to what i need to know? it seems like there are several options of coding styles but i'm afraid i might be mixing them together and getting errors. i would like very much to just find a straight forward guide of one style.

honestly, i have been on the web all day reading, testing... if my co-workers weren't still here, i may actually start to cry... i know enough about web development that if i can just get over this really brainless spot i'm in, i'll hit the ground running!!

For question #1, I'd say a definite yes, but that's just my opinion. About 60% of all problems that I've helped people with are because they're not using Visual Studio to code with (probably more in fact). VS is not that hard to learn, and does so much of the grunt work for you.

For Question #2, the tutorial here is not badhttp://www.asp.net/QuickStart/aspnet/Default.aspx I would highly recommend going through it step by step. Also there are some excellent books on the subject (Dino Esposito's comes to mind). And, of course, there's a lot of help available here once you get going.

NC...


dzr wrote:

1. I'm using Dreamweaver to develop with. Would it be better to use Visual Web Developer? Would the time spent learning that new interface be made up for since it's built specifically w/ asp.net. I'm not a super dreamweaver developer anyway- i have always hand coded using Homesite but my current job wants me in dreamweaver so...

Ditch Dreamweaver.... you are missing out on one HUGE aid in helping you learn: Intellisense

dzr wrote:

Of course the visual web dev. express i downloaded - I can't even figure out how to change the default Page Language="VB" to be C#.

When you create the page it'll give you a dropdown for C# or VB

dzr wrote:

2. does anyone know of any sort of quick-start guide to what i need to know?

Right at the top of this very page: "Tutorials"


OK! Now I'm rolling... sorta... I did a few step by step tutorials andI have a grip on the site creation, basic interface and I haveconnected to my database!

The interface is very cool and the debugging is fantastic. I am a biton the fuzzy side with any sort of WebAdministrator tasks -- It's beena while since I worked w/ ColdFusion/SQL Server so...

My plan is not to use roles, just simple login based on a User table.

string strConnection = "server=xxx;database=xxx;uid=xxx;pwd=xxxx;";
SqlConnection Connection = new SqlConnection(strConnection);
String strSQL = "Select * From user_admin";
SqlCommand command = new SqlCommand(strSQL, Connection);
SqlDataReader Dr;
Connection.Open();
Dr = command.ExecuteReader();
while (Dr.Read()) {

the while loop is where it stops saying "nvalid attempt to Read when reader is closed."
-- where i'm assuming it's not connecting to the DB and therefore has nothing to Read.

The reason I ask this to the forum is because, at one point, I haddifferent connection commands which caused an error - when I rightclicked on that error I saw a "Repair with ...?..." and I clickedok. I don't know what I did...l Anyway - if you want to look and let meknow if there's some thingreally easy you can tell me to fix, thatwould be great. ***don't spend any time on it though - I'll just dig inthe morning and find it... digging is good for learning...!

: ) But I do have a questions that I would be so so thankful if you gave meyour input on. I have setup the SQL tables and for some reason, cannotfind consistant advice on the best way to set up the unique ID. I wantit to be an autoincrement on insert kind of thing.

What I have finally settled on is the ID field being field type"int" with is identity=true, identity seed=1, identity increment =1.

The above seems to work perfect when I add a record in EnterpriseManager but since I cannot do an insert via the web, I can't test that.The big stress I'm having with it though is no matter what I try -- Icannot import any data into the tables... I have tried everywhich way configuration ofaccess,csv,tab delimeted....

I have 5 tables that need to be populated and the client gave me everything in XLS.

Oh! I have one more question...how long do I get to keep my copy ofVisual Web Developer ?

Ok.. .that's it for tonight.

You guys are great! !!!


Try this and see what happens:

string connectionString = "server=xxx;database=xxx;uid=xxx;pwd=xxxx;";
string sqlStatement = "Select * From user_admin";

SqlConnection dbConnection = null;
SqlCommand dbCommand = null;
SqlDataReader dbDataReader = null;

try
{
// Instantiate the Connection object...
dbConnection = new SqlConnection();
dbConnection.ConnectionString = connectionString;
// dbConnection = new SqlConnection(connectionString);
dbConnection.Open();

// Instantiate the Command object...
dbCommand = new SqlCommand();
dbCommand.Connection = dbConnection;
dbCommand.CommandText = sqlStatement;
dbCommand.CommandType = CommandType.Text;
// dbCommand = new SqlCommand(sqlStatement, dbConnection);

// Instantiate the DataReader...
dbDataReader = dbCommand.ExecuteReader();

// Write out the column names...
for (int i=0; i<dbDataReader.FieldCount; i++)
{
this.Response.Write("Column #" + i.ToString() + ": " + dbDataReader.GetName(i) + "<br>");
}

// Write out the column values...
while ( dbDataReader.Read() )
{
// dbDataReader.FieldCount is the number of columns/fields read.
// dbDataReader.GetName(i) is the column/field name.
// dbDataReader[i] is the column/field value.
// or dbDataReader["field-name"]

// Add the column values...
for (int i=0; i<dbDataReader.FieldCount; i++)
{
object currentObject = dbDataReader[i];
string currentValue = string.Empty;

if ( currentObject != System.DBNull.Value )
currentValue = currentObject.ToString();

this.Response.Write("Column #" + i.ToString() + ": " + currentValue + " ");
}

this.Response.Write("<br>");
}
}
catch(Exception ex){
this.Response.Write("Error: <br>" + ex.Message + "<br>" + ex.StackTrace + "<br>");
}
finally
{
// Close the DataReader...
if ( dbDataReader != null )
dbDataReader.Close();

// Kill the Command object...
if ( dbCommand != null )
dbCommand.Dispose();

// Close the Connection object...
if ( (dbConnection != null) && (dbConnection.State == ConnectionState.Open) )
dbConnection.Close();
}

NC...


I found this code that I used one time to populate a database from XML files, if it will help you:

string fileName = "xxxx.xml";

try
{
string filePath = System.Web.HttpContext.Current.Request.ApplicationPath + "\\" + fileName;
filePath = System.Web.HttpContext.Current.Server.MapPath(filePath);

DataSet dataSet = new DataSet();

// Reads the XML file into the DataSet...
dataSet.ReadXml(filePath);

DataTable dataTable = dataSet.Tables[0];

string sqlStatement = "INSERT INTO table-name-here ";

string columnStatement = string.Empty;
for (int i=0; i<dataTable.Columns.Count; i++)
{
if ( columnStatement.Length > 0 )
columnStatement += ",";
else
columnStatement += "(";

columnStatement += dataTable.Columns[i].ColumnName;
}
columnStatement += ") ";
sqlStatement += columnStatement;

string valuesStatement = string.Empty;
for (int i=0; i<dataTable.Rows.Count; i++)
{
System.Data.DataRow dataRow = dataTable.Rows[i];


// Loop through the columns for each row and grab the values...
for (int j=0; j<dataRow.Table.Columns.Count; j++)
{
if ( valuesStatement.Length > 0 )
valuesStatement += ",";
else
valuesStatement += "(";

valuesStatement += "'" + dataRow[j].ToString().Trim();
}
valuesStatement += ")";

string dmlStatement = sqlStatement + valuesStatement;
// this.Response.Write(dmlStatement + "<br>");

this.ExecuteDMLStatement(dmlStatement);
}

}
catch(Exception ex)
{
this.Response.Write("Error: <br>" + ex.Message + "<br>" + ex.StackTrace + "<br>");
}

public int ExecuteDMLStatement(string dmlStatement)
{
string connectionString = "server=xxx;database=xxx;uid=xxx;pwd=xxxx;";

SqlConnection dbConnection = null;
SqlCommand dbCommand = null;

int returnValue = 0;

try
{
// Instantiate the Connection object...
dbConnection = new SqlConnection();
dbConnection.ConnectionString = connectionString;
// dbConnection = new SqlConnection(connectionString);
dbConnection.Open();

// Instantiate the Command object...
dbCommand = new SqlCommand();
dbCommand.Connection = dbConnection;
dbCommand.CommandText = dmlStatement;
dbCommand.CommandType = CommandType.Text;
// dbCommand = new SqlCommand(dmlStatement, dbConnection);

// Execute the Command object...
returnValue = dbCommand.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
if ( dbCommand != null )
dbCommand.Dispose();

if ( dbConnection != null )
dbConnection.Close();
}

return returnValue;
}

NC...


this was incredibly helpful! i got it running just fine and now all i have to do is mix in my working validation code.

I did get an error on the "("Error: <br>" + ex.Message + "<br>" + ex.StackTrace + "<br>");" -- it didn't know what "ex" was. I also couldn't find where "Message" was setup. I took it out and all is well. I'll do some reading on try,catch & finally...

thank you SO much!

i'll be trying the xml trick next!!


Sorry, that's because thecatch line should becatch(Exception ex). I fixed the post for future readers.

NC...


ok thanks...

i got my login working and then i did a copy site and ftp'd all the files onto the web and now i'm getting that Server Error error again... i tried creating a new website - directly FTP'ing onto the server...same error.The new site zer0 code - just the blank outline that 'new site' creates and still error. i made an index.html that i can go to ok...??

i swear i'm almost independant!

Error:

Server Error in '/' Application.
Runtime Error
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.

Details: To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off".

my web.cofig looks like this:

<?xmlversion="1.0"?>

<configuration>

<appSettings/>

<connectionStrings/>

<system.web>

<roleManagerenabled="true" />

<compilationdebug="true"/>

<authenticationmode="Forms" />

<customErrorsmode="Off"defaultRedirect="GenericErrorPage.htm">

<errorstatusCode="403"redirect="NoAccess.htm" />

<errorstatusCode="404"redirect="FileNotFound.htm" />

</customErrors>

</system.web>

</configuration>


Did you set Debug="True" in the page directive?