Changing a DataGrid cell at runtime

stephen365

New Member
How do I programmatically change the contents/properties of a DataGrid cell at runtime? I'm trying to alter them row-by-row as the datagrid is bound. <BR>For a simple example, say I'm trying to change the BackColor of a cell depending on a certain condition. If the datasource field returns "Male", then change the BackColor to "Blue", otherwise change to "Pink".<BR>I tried calling my own function in the ItemDataBound event of the datagrid to do this, but it doesn't seem to work. Am I on the right track, or is there a better way?<BR><BR>Thanks,<BR>GregItemdatabound event is the best way to go. Create a function and check for your condition then change based on that. How was it not working before?I keep getting type conversion errors. In the ItemDataBound event, it won't let me do this,<BR><BR>e.Item.Cells(0).BackColor = "red"<BR><BR>It says, "String cannot be converted to System.Drawing.Color"<BR>I then tried,<BR><BR>e.Item.Cells(0).BackColor = CType("red", System.Drawing.Color)<BR><BR>but it still gives the same error.The best way to do that is like this:<BR>e.Item.Cell(0).BackColor = System.Drawing.Color.RedI have a Datagrid with a datecolumn which i want to change to red cellcolor i the date is older than today, and green otherwise. But I don't know where to put the IF-sentences and where to put e.Item.Cell(0).BackColor = System.Drawing.Color.Red..<BR><BR>I have following code in Codeview:<BR><BR> Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load<BR> ' Obtain categoryId from QueryString<BR> Dim Username As String = Request.Params("Username")<BR><BR> ' Obtain products and databind to an asp:datalist control<BR> Dim ShowAds As RentAdmin.SleepComp = New RentAdmin.SleepComp()<BR><BR> gridSleepAds.DataSource = ShowAds.AdsPerUser(Username)<BR> gridSleepAds.DataBind()<BR> End Sub<BR><BR><BR> Public Function AdsPerUser(ByVal Username As String) As SqlDataReader<BR><BR> ' Create Instance of Connection and Command Object<BR> Dim myConnection As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))<BR> Dim myCommand As SqlCommand = New SqlCommand("Adm_Sleep_Ads_PerUser", myConnection)<BR><BR> ' Mark the Command as a SPROC<BR> myCommand.CommandType = CommandType.StoredProcedure<BR><BR> ' Add Parameters to SPROC<BR> Dim parameterUsername As SqlParameter = New SqlParameter("@Username", SqlDbType.VarChar, 20)<BR> parameterUsername.Value = http://aspmessageboard.com/archive/index.php/Username<BR> myCommand.Parameters.Add(parameterUsername)<BR><BR> ' Execute the command<BR> myConnection.Open()<BR> Dim result As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConne ction)<BR><BR> ' Return the datareader result<BR> Return result<BR><BR><BR> End Function<BR>try with the following...<BR><BR>e.Item.Cells(0).BackColor = System.Drawing.Color.Red<BR><BR>Hope u will be successful<BR><BR>Veena
 
Back
Top