Home » VB.Net

How to Format Data in the Windows Forms DataGridView Control

hi all

i want to format columns of my datagridview.for example 20100630 ------>2010/06/30

this code doesnot work for me:

dataGridView1.Columns[2].DefaultCellStyle.Format = "YYYY/MM/dd";
thsnk s



20 Answers Found


Answer 1

Hello Babak_bsn,


    Just change YYYY into yyyy.

    dgtest.Columns["DOB"].DefaultCellStyle.Format = "yyyy/MM/dd";

  kindly, let me know if you need further help.


Paras Sanghani

Mark As answer if it helped you.


Answer 2

You could always replace one string with the other...

string mystring=20100630;



You get the drift



Answer 3

Thank you friends

here is my code,i changed my code but it doesn't work

SqlCommand cmd = new SqlCommand("SELECT * FROM City", new Setting().Getconn());
      SqlDataReader dr = cmd.ExecuteReader();
      DataTable dt = new DataTable();
      dataGridView2.DataSource = dt;
      dataGridView2.Columns[2].DefaultCellStyle.Format = "yyyy/MM/dd";


Answer 4

Replace the string as I said or tell the database how do you want the date or change the way the database store the date.


PS: I wrote this but it did not show :|


Answer 5

This way as you are trying to do is impossible. 

You will have to do it row by row when you are populating DGW (from dataTable - this is the best and simpliest way of holding data  in the code):

lets say when you populate the dateTimes in DGW`s column2:


  int row = -1;
  int column = 0;
  foreach (DataRow dr in table.Rows)
  column = 0;
  dataGridView1.Rows[row].Cells[column].Value = dr[0].ToString(); //the 1stcolumn of dataTable you want to populate (i dont know which it is)
  DateTime myDate = Convert.ToDateTime(dr[1]);
  string dateString = myDate.ToString('d'); //FORMAT OF: dd//MM/yyyy
  dataGridView1.Rows[row].Cells[column].Value = dateString;

or try this, that it will suit your needs:


string dateString = myDate.ToString("yyyy/MM/dd"); //FORMAT OF: dd//MM/yyyy


... but there might be one problem. Where from you you get this number? Is a dateTime value or is an integer?


Answer 6

Thank you Mitja

that's integer value that save in Table in DB


Answer 7

Thank you Serguey

i change the code as you say but it doesn't work too

DataGridViewCellStyle style=new DataGridViewCellStyle();
      dataGridView2.Columns[2].DefaultCellStyle = style; 


Answer 8

The problem is that the value 20100630 is not a valid DateTime, I mean the C# program wont recognize it as a valid date time.

So if you have any other option is ok, but if not, I can suggest you how to salve this problem:


int intDate = 20100630;
int a = 2010;
int b = 6;
int c = 30;
DateTime newDate = new DateTime (a,b,c);
string dateString= newDate.ToString("yyyy/MM/dd");


So now you have your time of a time :) and you just do:

dataGridView1.Rows[row].Cells[column].Value = dateSting;


btw, one friendly suggestion, please change the type of the "date"  in your database. Please use datetime". Would be way easier for you to use it.

thats all :)




Answer 9

Ouch, you are storing as an int in the database?

It would be easier to use datetime, then you could just tell the database to store in the yyyy/MM/dd format  and you wouldn't need a conversion.

borrowing from Mitja code

int intDate = 20100630;

string mystring=intDate.ToString();




PS: I'm not sure of the insert index, check them before hand



Answer 10

Do you know how to seperate the int 20100630 into 3 peaces (for year, month and day)?

And, if you always have 8 characters for "date"? I mean if you aways write integer with 8 characters, for example  if the day is 1st of July 2010 - do you write it as 20100701 or 201071? There is a lot of differences between these two integers. Specially if you want to seperate them into 3 peaces. 

If you know what I mean.

btw, I did get your previous post, and what about myString.Insert() method, whats this got to do here?


Answer 11

Are you asking me or him?  Sorry I'm a bit confused.



Answer 12

Ups, sorry, didnt realize you posted that post.

ok, so im asking you, if you are the owner of it. Just curious.


Answer 13

Hi experts thank you for your useful answers

i change type of my field into navarchar(50) (20100630 is now string)

then write this code:

DataGridViewCellStyle style=new DataGridViewCellStyle();
      dataGridView2.DataSource = dt;
      style.Format.Insert(3, "/");
      style.Format.Insert(5, "/");
      style.Format.Insert(7, "/");
      dataGridView2.Columns[2].DefaultCellStyle.Format = style;
but doesn't work. i want to show 2010/06/30 to user


Answer 14

1st of all you should change to DATETIME!

then when you change datime value to string you have to seperate value to 3 pieces (year, month, day). and only then you can change it to you type of string.

Let me try to do the code. wait


Answer 15

Ok, this is it. It works fine for me... this is the FULL CODE you can use:

 int row = -1;
 int column = 0;
 foreach (DataRow dr in table.Rows)
 column = 0;
 dataGridView1.Rows[row].Cells[column].Value = dr[0].ToString(); //the 1stcolumn of dataTable you want to populate (i dont know which it is)
 int intDate = Convert.ToInt32(dr[1]);
  char[] charABC = Convert.ToString(intABC).ToCharArray();
  string year = charABC[0].ToString() + charABC[1].ToString() + charABC[2].ToString() + charABC[3].ToString();
  string month = charABC[4].ToString() + charABC[5].ToString();
  string day = charABC[6].ToString() + charABC[7].ToString();

  string strDate = year + "/" + month + "/" + day;
  dataGridView1.Rows[row].Cells[column].Value = strDate;
 string dateString = myDate.ToString('d'); //FORMAT OF: dd//MM/yyyy
 dataGridView1.Rows[row].Cells[column].Value = dateString;

I just hope you insert 8 characters all the time. I mean if the month or the day has one number, you insert for January 01, and not 1. Be careful with that!

Hope I helped you.



Answer 16

One more question, can you mark this thread as Helpful on my name? No one so far hasn`t done this for me :) That green arrow just bellow my name.


If you have any other question, dont hasitate.

Best regards



Answer 17

There is no need to use that roundabout way of converting a string to a char[] to a string

Granted it would be better to simply change the type in the database and tell it how to store the date.

using insert on the string work

using System;
  public class SampleClass
    public staticvoid Main ( )
      int max=20100615;
      string mystring=max.ToString();


Answer 18


      int max=20100615;
      string mystring=max.ToString();

wow, until now I didnt know for this methos Insert. Great, I`ll remember that.

cheers Serguey123 :)


Answer 19


Why this doesn't work for me:

foreach(DataRow dtr in dt.Rows)
        int date=Convert.ToInt32( dtr[2]);
        string mystring = date.ToString();

        mystring.Insert(4, "/");
        mystring.Insert(7, "/");



Answer 20

foreach(DataRow dtr in dt.Rows)
    string mystring = (dtr[2]).ToString();

    mystring =mystring.Insert(4, "/");
    mystring =mystring.Insert(7, "/");



a Coworker from me complained that he got some wired Errors.
The Error he gets is:

Type 'System.Windows.Forms.Control' in Assembly 'System.Windows.Forms, Version=, Culture=neutral, PublicKeyToken=b77a5c561934089' is not marked as serializable.

I tryed, but failed to reproduce this Error on a different machine.
So I attached another VS instance to the one witch got this exception and got this Stacktrace:

>        mscorlib.dll!System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(System.RuntimeType type) + 0x3a3 bytes    
        mscorlib.dll!System.Runtime.Serialization.FormatterServices.GetSerializableMembers(System.Type type, System.Runtime.Serialization.StreamingContext context) + 0xf8 bytes        
        mscorlib.dll!System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() + 0xa1 bytes        
        mscorlib.dll!System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(object obj, System.Runtime.Serialization.ISurrogateSelector surrogateSelector, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.Formatters.Binary.SerObjectInfoInit serObjectInfoInit, System.Runtime.Serialization.IFormatterConverter converter, System.Runtime.Serialization.Formatters.Binary.ObjectWriter objectWriter, System.Runtime.Serialization.SerializationBinder binder) + 0xdb bytes        
        mscorlib.dll!System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(object obj, System.Runtime.Serialization.ISurrogateSelector surrogateSelector, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.Formatters.Binary.SerObjectInfoInit serObjectInfoInit, System.Runtime.Serialization.IFormatterConverter converter, System.Runtime.Serialization.Formatters.Binary.ObjectWriter objectWriter, System.Runtime.Serialization.SerializationBinder binder) + 0x37 bytes        
        mscorlib.dll!System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(object graph, System.Runtime.Remoting.Messaging.Header[] inHeaders, System.Runtime.Serialization.Formatters.Binary.__BinaryWriter serWriter, bool fCheck) + 0x21f bytes       
        mscorlib.dll!System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(System.IO.Stream serializationStream, object graph, System.Runtime.Remoting.Messaging.Header[] headers, bool fCheck) + 0x86 bytes        
        mscorlib.dll!System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(System.IO.Stream serializationStream, object graph) + 0xe bytes 
        System.Windows.Forms.dll!System.Resources.ResXDataNode.FillDataNodeInfoFromObject(System.Resources.DataNodeInfo nodeInfo, object value) + 0x395 bytes 
        System.Windows.Forms.dll!System.Resources.ResXDataNode.GetDataNodeInfo() + 0xc4 bytes     
        System.Windows.Forms.dll!System.Resources.ResXResourceWriter.AddDataRow(string elementName, string name, object value) + 0x139 bytes     
        System.Windows.Forms.dll!System.Resources.ResXResourceWriter.AddResource(string name, object value) + 0x62 bytes     
        System.Design.dll!System.ComponentModel.Design.Serialization.ResourceCodeDomSerializer.SerializationResourceManager.SetValue(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, string resourceName, object value, bool forceInvariant, bool shouldSerializeInvariant, bool ensureInvariant, bool applyingCachedResources) + 0x10b bytes     
        System.Design.dll!System.ComponentModel.Design.Serialization.ResourceCodeDomSerializer.SerializationResourceManager.SetValue(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, System.ComponentModel.Design.Serialization.ExpressionContext tree, object value, bool forceInvariant, bool shouldSerializeInvariant, bool ensureInvariant, bool applyingCachedResources) + 0x231 bytes        
        System.Design.dll!System.ComponentModel.Design.Serialization.ResourceCodeDomSerializer.Serialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, object value, bool forceInvariant, bool shouldSerializeInvariant, bool ensureInvariant) + 0x2c0 bytes       
        System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializerBase.SerializeToResourceExpression(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, object value, bool ensureInvariant) + 0xee bytes    
        System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializerBase.SerializeCreationExpression(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, object value, out bool isComplete) + 0x1bd bytes   
        System.Design.dll!System.ComponentModel.Design.Serialization.ComponentCodeDomSerializer.Serialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, object value) + 0x5f8 bytes  
        System.Design.dll!System.Windows.Forms.Design.ControlCodeDomSerializer.Serialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, object value) + 0x83 bytes   
        System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializerBase.SerializeToExpression(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, object value) + 0x173 bytes  
        System.Design.dll!System.ComponentModel.Design.Serialization.PropertyMemberCodeDomSerializer.SerializeNormalProperty(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, object value, System.ComponentModel.PropertyDescriptor property, System.CodeDom.CodeStatementCollection statements) + 0x1aa bytes      
        System.Design.dll!System.ComponentModel.Design.Serialization.PropertyMemberCodeDomSerializer.Serialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, object value, System.ComponentModel.MemberDescriptor descriptor, System.CodeDom.CodeStatementCollection statements) + 0x137 bytes      
        System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializerBase.SerializeProperty(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, System.CodeDom.CodeStatementCollection statements, object value, System.ComponentModel.PropertyDescriptor propertyToSerialize) + 0xdb bytes     
        System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializerBase.SerializeProperties(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, System.CodeDom.CodeStatementCollection statements, object value, System.Attribute[] filter) + 0x15d bytes        
        System.Design.dll!System.ComponentModel.Design.Serialization.ComponentCodeDomSerializer.Serialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, object value) + 0xb53 bytes 
        System.Design.dll!System.Windows.Forms.Design.ControlCodeDomSerializer.Serialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, object value) + 0x83 bytes   
        System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializerBase.SerializeToExpression(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, object value) + 0x173 bytes  
        System.Design.dll!System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.Serialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, object root, System.Collections.ICollection members) + 0x178 bytes        
        System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformFlush(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager) + 0x7e bytes 
        System.Design.dll!System.ComponentModel.Design.Serialization.BasicDesignerLoader.Flush() + 0xfe bytes 
        Microsoft.VisualStudio.Design.dll!Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.Flush() + 0x76 bytes   
        System.Design.dll!System.ComponentModel.Design.DesignSurface.Flush() + 0x21 bytes     
        System.Design.dll!System.ComponentModel.Design.DesignerHost.OnActiveDesignerChanged(object sender, System.ComponentModel.Design.ActiveDesignerEventArgs e) + 0xad bytes  
        System.Design.dll!System.ComponentModel.Design.DesignerEventService.OnActivateDesigner(System.ComponentModel.Design.DesignSurface surface) + 0x107 bytes 
        System.Design.dll!System.ComponentModel.Design.DesignSurfaceManager.ActiveDesignSurface.set(System.ComponentModel.Design.DesignSurface value) + 0x2a bytes    
        Microsoft.VisualStudio.Design.dll!Microsoft.VisualStudio.Design.VSDesignSurfaceManager.Microsoft.VisualStudio.Shell.Interop.IVsSelectionEvents.OnElementValueChanged(uint elementid, object varValueOld, object varValueNew) + 0xeb bytes   
        [Native to Managed Transition]        
        [Managed to Native Transition]        
        Microsoft.VisualStudio.Platform.WindowManagement.dll!Microsoft.VisualStudio.Platform.WindowManagement.WindowFrame.ConnectSelectionContext() + 0xaf bytes    
        Microsoft.VisualStudio.Platform.WindowManagement.dll!Microsoft.VisualStudio.Platform.WindowManagement.WindowFrame.Activate() + 0x118 bytes  
        Microsoft.VisualStudio.Platform.WindowManagement.dll!Microsoft.VisualStudio.Platform.WindowManagement.WindowManagerService.viewManager_ActiveViewChanged(object sender, Microsoft.VisualStudio.PlatformUI.Shell.ActiveViewChangedEventArgs e) + 0x23c bytes     
        Microsoft.VisualStudio.Shell.10.0.dll!Microsoft.VisualStudio.PlatformUI.ExtensionMethods.RaiseEvent<System.__Canon>(System.EventHandler<System.__Canon> eventHandler, object source, System.__Canon args) + 0x14 bytes     
        Microsoft.VisualStudio.Shell.ViewManager.dll!Microsoft.VisualStudio.PlatformUI.Shell.ViewManager.SetActiveView(Microsoft.VisualStudio.PlatformUI.Shell.View view, Microsoft.VisualStudio.PlatformUI.Shell.ActivationType type) + 0x9e bytes     
        Microsoft.VisualStudio.Shell.ViewManager.dll!Microsoft.VisualStudio.PlatformUI.Shell.ViewManager.OnTabItemMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs args) + 0x49 bytes   
        Microsoft.VisualStudio.Shell.ViewManager.dll!Microsoft.VisualStudio.PlatformUI.Shell.ViewManager..cctor.AnonymousMethod__16(object sender, System.Windows.Input.MouseButtonEventArgs args) + 0x36 bytes   
        PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget) + 0x31 bytes   
        PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target) + 0x36 bytes   
        PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) + 0x40 bytes   
        PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) + 0x133 bytes        
        PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args) + 0x79 bytes        
        PresentationCore.dll!System.Windows.UIElement.RaiseTrustedEvent(System.Windows.RoutedEventArgs args) + 0x41 bytes     
        PresentationCore.dll!System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs args, bool trusted) + 0x42 bytes  
        PresentationCore.dll!System.Windows.Input.InputManager.ProcessStagingArea() + 0x1ff bytes     
        PresentationCore.dll!System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs input) + 0x45 bytes    
        PresentationCore.dll!System.Windows.Input.InputProviderSite.ReportInput(System.Windows.Input.InputReport inputReport) + 0x62 bytes     
        PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.ReportInput(System.IntPtr hwnd, System.Windows.Input.InputMode mode, int timestamp, System.Windows.Input.RawMouseActions actions, int x, int y, int wheel) + 0x263 bytes       
        PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.FilterMessage(System.IntPtr hwnd, MS.Internal.Interop.WindowMessage msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) + 0x46d bytes        
        PresentationCore.dll!System.Windows.Interop.HwndSource.InputFilterMessage(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) + 0x75 bytes 
        WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) + 0xbe bytes 
        WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) + 0x7d bytes     
        WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs) + 0x53 bytes 
        WindowsBase.dll!MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(object source, System.Delegate method, object args, int numArgs, System.Delegate catchHandler) + 0x42 bytes      
        WindowsBase.dll!System.Windows.Threading.Dispatcher.InvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs) + 0xb4 bytes       
        WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam) + 0x104 bytes   

Any idea what may be wrong, what other thing I could check?
Remark: We do have some Controls we develop our self, but the Error/Stack looks too genereric to me to say if our controls are involved.


I have the code which checks if there is a selected tab


Private Function GetBrowser() As WebBrowser
  If TabControl1.SelectedTab IsNot Nothing Then
   For Each c As Control In TabControl1.SelectedTab.Controls
    If TypeOf (c) Is WebBrowser Then
     Return c
     Exit Function
    End If
  End If
  Return Nothing
 End Function

Since I am trying to code better, I turned Option Strict On, and now it disallows implicit conversions from 'System.Windows.Forms.Control' to 'System.Windows.Forms.Webbrowser'. The
is giving this error. Can someone help me? Sorry for my bad english.




I'd like to use a TreeView control to display database data in a windows form with VB2008. All the information what I found is related to a website design, but I'm working on a database program (sql2005), where I'd like the user to see the structure what he/she make up with a TreeView like control. Just something like that when you explore your hard disk.

How can I do that?




i don't know why when i click the button in popup window form then call parent form's method and pass datatabel in popup to parent's data
finally bind to parent form's datagridview. but why when click the button i can pass the datatable but can't bind to datagridview. why????

code as belows:


  private void btnOK_Click(object sender, EventArgs e)
            parentForm PF = new parentForm();


   public  void getDatatable()
            popupForm pp = new popupForm();

            this.dt_ = pp.dt;
           this.dgv1.DataSource = this.dt_;



Please I want to know how I can change the back color of a row based on a cell value using CellFormating event.  The cell visible property is set to false.


Trying to deploy an application written in VB.NET.  First had an issue with not including the PowerPacks that went away and the application installed correctly once I included them as a prerequisite.

However, now once the user logs into the application the main menu just bombs out and the application quits without returning an error message.  I suspected it might be the DataGridView control and had those suspicions verified when I changed the application's startup form to be one that does not contain the grid and it loaded just fine.

Has anyone experienced this problem before?  Is there a prerequisite or reference I need to include in the build?

Mousing over the control reveals that it is "DataGridVersion from Microsoft Corporation .NET component".

Thanks in advance.



I have a form2 in which I am passing data to Form using the Constructor method.

privatevoid OKbtn_Click(object sender, EventArgs e)
      Form1 frm = new Form1(txtRead.Text, pictureBox1.Image);

In Form1, I initialized another constructor,

public Form1(string strTextBox, Image PicFile)
    lb.Text = strTextBox;
    pictureBox1.Image = PicFile;
In the Form1, I have a TableLayout in which each cell has a picture box and a label. These cells are created at runtime when the user specifies the number of rows and columns. Clicking on any of these PictureBox opens Form2. A user sets some Text and an Image in Form2. Now on pressing the OK button, the data is sent to the Form1. I have to send the image to the PictureBox in the Cell and the Text to the Label in the cell. However, I am not aware of the name of the controls since they are created at runtime? What should I do in this case?


 I am using a from  view for data entry.  I need to verify that a check box is true or false after editing a record.

I have been accessing label text using the following|

CType(FormView1.FindControl("RespDeptLabel"), Label).Text


How can I access the state of  a checkbox in the form view to determine if it is true or false


I have customized a Page Layout to include a custom Data Form View Web Part that will allow users to enter comments on a news story page in a publishing site.

I was having a difficult time because when I clicked the button to save the data to the list, everything saved correctly, but the control was redirecting me to the AllItems.aspx page of the list.  This wasn't the desired behavior since the end user would prefer to see that their comment was posted on the news story page and wouldn't know what the AllItems.aspx page was for.

The save button that was created in the XSL seciton of the web part was:

<SharePoint: SaveButton runat="server" ControlMode="New" id="savebutton1" />

Microsoft has documented a RedirectUrl property on this button that I figured could change what page was loaded after the user saved the form data.  However, try as I might I could not get it to work.

Some more searching lead me to this article:


Which details how to create a "Form Action" for a save button rendered in the XSL of a DataFormWebPart.  This was a great article, but it doesn't detail the code that Sharepoint Designer outputs for this action.  After following the instructions, I discovered this code for a button:

<input type="button" value="Save" name="btnSave" onclick="javascript: {ddwrt:GenFireServerEvent('__commit;__redirect={}')}" />

When used instead of my SharePoint: SaveButton above, the form saved it's data correctly, and the current page that the form was submitted from was reloaded for the user.

You could also put any URL in the __redirect={} that you want, for example __redirect={http://www.google.com} or __redirect={/news/PressReleases/}

Notice that there are no quotes around the URLs passed into the __redirect directive.

Didn't find this documented anywhere, but it seemed pretty useful so I thought I would share.




is it true that if the AllowEdit property is set to false, any DataGridViewComboBoxColumn that my DataGridView has will be in a "disabled state" (will not allow the user to change the value of the DataGridViewComboBoxColumn) AND there is no way i can make it in an "enabled state" unless i switch the AllowEdit to true?


after clicking the button in popup window form then i will get the datatable in popup window form and bind to opener's datagridview. but i don't know why when i close the popup window,i can't refresh opener's window to display data in dgv.

anyone help~ 


Has anyone experienced a case where a .Net Windows Forms app caused severe desktop flicker?

I have a Windows Forms app (.Net 3.5 , C#) with a datagridview in a usercontrol. Occasionally, while running other applications at the same time (I see it with Louts Notes, but the worst behavior is a user with Reuters Bridge Station) , switching to my app and then to the other app causes the entire desktop to flicker, freezing all user interactions, from a few seconds to close to a minute. (All users using Windows XP Professional) This happens even with a small amount of data in the grid I am not doing any custom painting in the app, and I am pretty certain none of my code is running at this time to call any refreshes or repaints.

I have already enabled double-buffering, so that's not the solution.

One interesting thing I found (in a MS forum) is that setting the TransparencyKey of the form will solve the problem - sometimes. (specifically for the Louts Notes users, but not for the Bridge Station users.) The users still affected are working around it by minimizing the app after data entry, before switching to the other apps. Any ideas will be greatly appreciated, as I am pulling out my hair over this. And I do not have too much hair to start with.




I am developing an application that loads a spreasheet to a datagrid, i then add a column (with data) dynamically in the datagrid. How can I take the data in the whole datagrid and display it in a new spreadsheet. Please help!


Hi! I want to add paging functionality to the datagridview in my windows form. I did a search in google and got some codes too but I am not able to implement in my code as the way I am binding data to gridview is different than the one shown by other codes (that i got from google). I have implemented update and delete also. So I dont want to alter my code but I need to add extra code to implement paging which i don't know. Could you help me guys? Code will be helpful.


My code for binding gridview is as follows

Private Sub FillString()

    If Trim(txtValue.Text) = "" Then
      sql = "SELECT * FROM AC"
      sql = "SELECT * FROM AC WHERE " & _
            cboDetailItems.SelectedItem & " Like '%" & _
            txtValue.Text & "%'"
    End If

  End Sub

  Public Sub LoadData()

    Dim connectionString As String = "my connection string"
    conn = New SqlConnection(connectionString)
    da = New SqlDataAdapter(sql, conn)
    ds = New DataSet()
    Dim commandBuilder As SqlCommandBuilder = New SqlCommandBuilder(da)
    da.Fill(ds, "AC")
    bsource.DataSource = ds.Tables("AC")
    grdACHistory.DataSource = bsource
    lblNoOfRecords.Text = String.Format("{0} Records Found", ds.Tables("AC").Rows.Count)

  End Sub


hello friends

Can any one tell me please how can we add the radio button in datagridview in window forms 


I have a datagridview in my win form 

It has a calander cell which populate on first cell click means any row cell (0) . 

dgv has allowusertoaddrow property true .

I used the code http://msdn.microsoft.com/en-us/library/7tas5c80.aspx for calander cell

now the problem is when I change the value of calander cell . and leave the cell .

instead of adding a single blank row it add three rows. and first two rows have the values for the autoincrement column and last row is full blank..


I trace the addrow event and it is firing three times .


I do not understand why it is happning ..

pls help




Now iam using sharepoint server 2007, here DocumentLibrary is having some files.

i need to display these files information into datagridview of windows forms application.

where datagridview columns are like

type        name (file name)   modified (date)        modifiedby     checked out to


i have the code like...



privatevoid button1_Click(object sender, EventArgs e)






using (SPSite oSite1 = newSPSite("http://abcd:39050"))




using (SPWeb oWebsite2 = oSite1.OpenWeb("/"))




SPDocumentLibrary docLib1 = (SPDocumentLibrary)oWebsite2.Lists["DLIP"];



SPListItemCollection items1 = docLib1.Items;



foreach (SPListItem item in items1)


// here code is required...........,please suggest me................








I'm writing a User control where i'm displaying a windows form on click of a button and the Form contains a DataGridView. This dataGridview would typically contain 4000-5000 no of records. Now when i'm resizing the Form i can see the VERY NOTICIBLE flickering effect. How can i reduce it? Any suggestions......????

[NOTE] I have set the DOCK property of the DataGridView to FILL so that on resize of the FORM the dataGrid should be resized to cover the full Form Area.


We have a .NET Grid control written with VC 7.1 SP1 and the 1.1 Framework.  This Grid Control wraps around an MFC Grid Control which is derived from a templatized class for dynamic object creation, i.e. regular grid vs. a hierarchical grid construction based on a flag. This Grid Control currently uses PInvoke to pass messages from the native code to the managed code and vice verse. 

We have a Microsoft Partner customer who needs to have us [urgently] port this older control to VC 9.0 SP1 and the 3.5 .NET framework. So we are "stuck" using the current PInvoke archictecture for this port rather than rearchitecting to take advantage of System.Runtime.InteropServices. Currently we are developing this port on Windows XP SP3 with MSVS 2008 SP1 with the 3.5.3709.* framework.  We have ported both under the /clr:old_syntax compiler option as well as the /clr: option.  With the /clr option version of this ported code, we have rewritten the old managed C++ extension syntax to use the C++/CLI managed C++ syntax.  With the /clr:old_syntax ported code, we have made minor syntactic changes, e.g. added AFX_MANAGE_STATE to the native code to avoid afxwin1.inl asserts, etc.

Both compile, build and link without error under /W3 option.   However, we are running into runtime behavior issues when we try to run the control on a WinForm in C#.   The Grid control .NET wrapper and it's underlying MFC Grid control are created and initialized successfully, the WinForm adds this created control to the ControlCollections successfully, but when the WinForm goes through the RunMessageLoop and RunMessageInnerLoop, the grid fails to draw on the WinForm.  We do override the WndProc in the both the .NET wrapper control as well as the MFC control. 

We suspect a message passing issue but cannot see nor narrow down the issue.

We are also having DesignMode issues as the control will not load from DesignTime.  We define and use our own designer and serializer by deriving from ScrollableControlDesigner and CodeDomSerializer, respectively.  In fact, both drag and drop of the control onto the WinForm as well as viewing a WinForm.cs, which contains a grid control object from code, in DesignMode causes a crash in the Designer.

Any expedited help is appreciated as our MS partner customer is anxious to meet their deadlines.

If needed we can create a WebEx session to step through and demonstrate these issues in detail.

Thank you,

Clayton Dean


I have a subform in continuous form view. I want a textbox control to change format depending on its displayed value:

Private Sub Form_Current()
    If Me.Status = "EXPIRED" Then
        Me.Status.ForeColor = vbYellow
        Me.Status.BackColor = vbRed
    ElseIf Me.Status <> "EXPIRED" Then
        Me.Status.ForeColor = 0
        Me.Status.BackColor = vbWhite
    End If

End Sub

The problem is that all records need to display "EXPIRED" in order for the format change to work. If one record is "EXPIRED" and another is <> "EXPIRED" then the format doesn't change for the one that's "EXPIRED".

How can I make the format change for the "EXPIRED" records?



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure