Home » Visual Studio

Auto generate a number in a text box in Infopath Form

Hello All,

I have a requirement of generating the auto number in one of the InfoPath form field(text box).I am designing this infopath form for Change Request in the organization.Can anyone help me  in doing it.

I appreciate your response.


Thank you,



14 Answers Found


Answer 1


You can create a sequence, Query the list and get the number  in the field:

using (SPSite site = new SPSite(siteUrl))
                        using (SPWeb web = site.OpenWeb())
                            // Get all the entries in the Ticket List
                            SPWeb oWeb = SPContext.Current.Web;
                            SPList oList = oWeb.Lists[listName];
                            SPQuery regQuery = new SPQuery();
                            regQuery.Query = "<Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query>";
                            items = oList.GetItems(regQuery);

Now you would have the list elements in datatable items.

Get the last record so that you have the latest number.

Add +1 to the number and you would get the next number.

Set the textbox value in InfoPath VSTA:


 public XPathNavigator GetCurrentXPathNav(String XPath)
            XPathNavigator DataSource = MainDataSource.CreateNavigator();
            XPathNavigator XPathNav = DataSource.SelectSingleNode(XPath, NamespaceManager);
            return XPathNav;



Answer 2

Hello Pradeep,

Thank you for your response.I am new bie in infopath  forms.Can you say me where to write this code.Do i need to write this in the Submit button of my infopath form.

I appreciate your time and help.

Thank you,



Answer 3


You have to configure your server:


Then follow:



In the InfoPath: Tools> Form Options> Programming > set the programming language.


Tools > Programming > Loading Event.

This will open VS.



Answer 4

I don't consider it wise to tell a newbie to immediately add code to their form.  There are non-code methods for doing many things, and there are likely multiple ways to go about creating unique IDs without code.  I just don't think it's good to immeidately go to a code solution and continue to propose that after the person says they are a newbie and don't know where to put the code - it is not a good way to give advice, imo.  He likely doesn't even have Visual Studio installed.

Smith, in my opinion, this is very easy to do without code as long as your ID does not have to be in the filename.  If that's the case, then here are the simple steps:

1) First, incorporate my Auto-Generating Filenames method.  Make sure that when you publish your template with this method that you promote the strFilename field so that it's saved into the form  library.

2) Next, create a new data connection to Receive from your Change Request form library (the same one where the form originates).  In this data connection, choose the ID and strFilename fields for retreiving.  Set the data connection NOT to automatically retrieve - we will only do it on demand during the initial Submit.

3) In your custom (non-code) submit button within the submit rule that you created as part of my blog, add a few actions.  Before the Close action but after the Submit action, add an action that queries the DC from step #2.  Then, add an action that sets your custom ID field to the ID of your DC from #2 but filtered where the strFilename field of the DC (SharePoint) is equal to the strFilename of the main data source (form).  After that, add another Submit.  The effect of the above actions will be that you submit the form with an auto-generated filename, then the form queries the form library, the returned data set includes the form you just submitted and includes the unique ID of that form,  you set the custom ID field of your form to the ID of the form you just submitted, and then you re-submit so that your CustomID field is populated, and then it closes.  If you want your custom ID to be something special like 1000-01, then you just need to use a concatenate formula in the action where you set the custom ID field.


Answer 5

When new item is added to SharePoint List or Library, then SharePoint creates unique ID number  and insert it to column named “ID”. It means SharePoint does generating  number automatically for you. Therefore, we can use this “ID” column in List or Library.

First, Create a new data connection as receive data from your SharePoint form  Library.

-          Select “ID” field in Data Connection Wizard. When query occurs, ID field value in Form Library will be returned to InfoPath form.

Second, let’s use your data connection

-          Go to Tools à Form options à Open and Save à Click Rules in Open behavior

-          Add action (Set a field’s value) à Put target field in Field à Click function button in Value à Click “Insert Function..” à Select “max” in Math category à You will have a string “max(double click to insert field)” in Formula field à double click underlined text à change  your data source to Secondary data source which you just created à select ID and click “OK”. à Add “+1” à your Formula field will be look like “max(@ID) + 1”. à Click ok.


Max(@ID) will return biggest ID value in Library and +1 will increment biggest ID value by 1.


??? - http://blog.naver.com/lightyea/

Answer 6

Hello Pradeep,

I know how to configure and start VSTA.So i got to know from your reply that i need to write it in Loading event.Thank you.

Thank you Clyaton too.I am looking into the information you have posted me.



Answer 7

SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();

#region Get ID
	using (SPSite oSite = new SPSite(mySite.ID))
 		using (SPWeb oWeb = oSite.OpenWeb(myWeb.ID))
			SPQuery oQuery = new SPQuery();
       oQuery.RowLimit = 30;
       SPList oList = oWeb.Lists["yourListName"];
       SPListItemCollection collListItems = oList.GetItems(oQuery);

       oWeb.AllowUnsafeUpdates = true;
       oListItem["YourColumName"] = Convert.ToString(Convert.ToInt32(oListItem["YourColumName"].ToString()) + 1);
       oWeb.AllowUnsafeUpdates = false;
       setNodeValue("/my:myFields/my:YourTargetNode", oListItem["Number"].ToString());

#region Set node value
public void setNodeValue(string path, string value)
   XPathNavigator root, infopathNode;
   root = this.MainDataSource.CreateNavigator();

    infopathNode = root.SelectSingleNode(path, this.NamespaceManager);
    if (infopathNode.MoveToAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance"))

   catch { }

Clayton and I provide your how to do it without code.

If you like to use code, then refer mine or Pradeep. Use setNodeValue() to set not value after you create/get uniqe number

??? - http://blog.naver.com/lightyea/

Answer 8

Sangha, that method requires that the default view has the item with the most recent ID, which also requires that the most recent item is never deleted.  My method cannot get the wrong ID.

Answer 9

Thank you Clayton, that’s good point.

My approach needs at least one item in List/Library

??? - http://blog.naver.com/lightyea/

Answer 10

Sangha / Clayton,

We can always set a condition that if the list is empty, set the default value whatever is required.



Answer 11

Another problem is that if you do it on form  Load, someone else may have submitted a form before you click Submit on yours, so you always need to run queries like this INSIDE your submit button.  The query to get Max(ID) must occur milliseconds before the submit action, so I recommend never doing it on Form Load.

One item in the library is not enough either.  It has to be the MOST RECENT ID, otherwise you get an ID that has already been used.  The default view may not show all items, it may not show the most recent item, and the most recent item may have been deleted.  It's best to submit, retrieve the ID of the form you submitted, then use that ID.  Otherwise, it's a risk.


Answer 12

That doesn't work either, because the default view may be empty, but that doesn't mean the list or library is empty.  Even if it is empty, it may not be a brand new list.  Deleting items doesn't restart the sequential ID numbering, which is again why you must get the ID of the current item by submitting it first and then retrieving the ID.  This works wonderfully unless there is a requirement  to put this ID in the filename, which I recommend not doing.

Answer 13

To assign a unique number  to form, I think that can be managed by creating a workflow . Try below steps. Would be easy users familar with creating simple WF using SPD.

Insert a Texbox in your infopath  form, "formNumber" and apply read only.  While publishing the form  ensure this field is made available to your list and  mark this field is allowed for edit.

- Create a New WF. Attach this worlflow to your "List"

- Set WF start option as "Automatically start when new items is created"

- Create an Action  "Set Field in Current Item".    Cilck on "field" and select "formNumber".  click on "value" then click on "fx" button.  select "Current Item" as  source and select "ID" as Filed.

Hope this will help



Answer 14

All that does is duplicate the built-in ID in a different field.  You don't need to do that when the ID is already created by SharePoint and stored in the form  library.  You can simply retrieve that ID into the form the moment it is submitted without the need for a workflow.




I have a browser form with a multi line text box. The height is set to be AUTO. Within the client all is fine. When opened as an administrator approved form the text box automatically adds a new line for every 20 characters you type.


So if you type 40 characters without pressing enter you get 2 blank lines appear under you text that you CANNOT remove.


I have tested this on a new form with various multi line text boxes. The width setting is unimportant, the spell check setting is unimportant.


If i fix the height then the issue goes away but this is not any good.


I cannot use rich text boxes as i have around 40 text boxes on the form and if they are rich text they take around 10 minutes to load in the browser (this is another issue i have)


Thanks in advance




I created an infopath form that would auto generate a number to each form from following instructions at the following site.


I am wondering if it is possible to change the starting point of the ID field within sharepoint.  It starts at 1.  I would like it to start at 1000. and add 1 number each time a new infopath form is added. Or would I add a different field to accomplish this.


Could someone please confirm if this is a bug.

I created an InfoPath form in 2010. As an Infopath form, the multiline textbox grows, as a user enters text, automatically as expected.

The very same form as a web form:

In IE 7 and IE 8 the box expands at every 20 or so chharacters instead of at the end of a line.

In Firefox (3.xxx) the box does not expand unless you press enter at the end of every line.

In IE 7 and IE 8 if you open a form that was created with FireFox, the boxes end up expanding as if it had been entered in IE instead of FireFox. FireFox seems to be the most compatable but how do I explain to user that they can use IE for everything but forms?

The question is this: Is it a bug because I would think the box should be dynamic as the user eneters data and should not require the user to press enter. When will this be fixed. It is holding us up as to ever being able to use InfoPath Web based forms which is a requirement because InfoPath based forms are not supported on any OS other than Windows. Web Based forms should operate and be available regardless of the browser type. Please advise.


I'm using a multi-line textbox in my infopath form, the text scorlls when user enter texts that exceed the width/height of the text box, thats fine. But after user submits the form, the textbox just dsiplays one line of text with with "..." at the end and user needs to use "End" key or drag the text using the mouse key to see the remaining text. We want to display all the text that user entered instead of "...". What setting needs to be done in the inforpath forms.

Also I wanted to know if there is any known issue using Rich Text field in Infopath form with SharePoint InfoPath service.

Thanks in advace,

I found an issue when testing existing InfoPath 2007 forms via the Infopath 2010 Designer client.  Integer fields in the form template are publishing to a SharePoint Forms Library and show in the default view.  However, if that library is then used as a Data Connection in another or same form template those integer fields are not displaying or available for selection. 

This is not a problem using the InfoPath 2007 client.  It is not an option to convert the field to text as it could affect existing forms in existing libraries.  Also, existing integer fields are no longer appearing in previously defined SharePoint-based secondary data connections.  Only the ID field still appears.  But, those existing fields still work in the form and are selectable for functions, etc.

Is there a solution to this?

Thanks much!  Mike - www.ProgramNetInc.com




Iam working with Rich Text Box in WPF. Iam using Rich Text box as word document in my application.I applied bullets/numbers to the  some text in Rich Text box.When I was deleting the same text,still one bullet/number is available in the word document i.e., in Rich Text box.

Steps to Produce :

1.Selected the Bullets or numbers from the tool bar of the merge document .

2.Enter some text and then select the total text with bullets or numbers and then press Delete from keyboard.

3.observe that text is deleting but for bullets/numbers,it is not completly deleted(one bullet or number is still available in the document i.e.,in Rich text box) .

This is Urgent requirement for us. Please, Give a solution for this problem



Infopath 2007
Browser Enabled
Sharepoint List in a Repeating table

I have a view with a Sharepoint List showing in a repeating table. I have conditional formatting to hide items that should not show based on Line Total.

Line Total = 4

Approver    Min Amount        Max Amount  
Jim                      3                  9
Jack                    1                   7
Sally                   2                    5

Based on this, I need to sort the Approvers based on Max Amount and send an email to them in order of the sort.  Is this possible?

We are working on a IT support site within the SharePoint and are wondering if there is a way for SharePoint to generate automatic ticketing numbers so issues can be tracked by a case/file number?


CRM auto generates code for case number attribute, however lenght of the number part has 5 as limit restriction.

Here I have a requirement to increase that to 6

Any idea how to do it ?




I have an infopath form in my document library and I have list with columns Service ID and Service Name.

Base on the service id i need to generate another request id for the form starting from 0 for each service id as follows.

service 1---Id-1)Request form          

            ----Id-2)Request form  


service 2---Id-1)Request form

            ----Id-2)Request form  

Any little help would be much appreciated.





I am developing a console application. This application generates a self signed certificate and installs it in the current machine's certificate store. 

The steps invlolved are :- 

1) Generate a certificate

2) Create a pfx file

3) Install the pfx file


For these steps i would need a password for protecting the private key and the pfx file.

However these passwords are used only during the execution of the exe.

Should I auto generate a password using some random number generation algorithm or accept the password as input from the user?


What are the security issues involved in both the scenarios ?







I know this should be easy

I have successfully created a combo box with Row Source

SELECT [Vendeurs].[VendeurID], [Vendeurs].[Last Name], [Vendeurs].[First Name] FROM Vendeurs;

From this I can select the First Name and Last Name from the table [Vendeurs]

I want to add a text box for First Name - that will display from the same table [Vendeurs] based on the Last Name selected in the Combo Box called [Last NameC]

I need to be able to read common delimited text that the user enters into a text box.  For example the text box would look like this:

I need to be able to read the lines and put the data into a multi-dimension array with all the first values in column 1, all the second values in column 2, and all the thrid values in column 3. 

Can anyone explain how to do this??



I have a report parameter where a user can enter a user name. We have 30K users in our environment and therefore we cannot use a drop down box.


Is there any possibility of an Ajax style auto-suggest textbox?


Hi All

i am Working on Text Value to Convert Automatic in Date

hear is my Value which put in Text Box i need to Convert This value to DATE

Ex. Value ONE is "1-7" or "1/7" or "1.7" or "01-07" or "01-07" or "01.07" when i put this value is automatic Convert in Date "01-07-2010"

Value TWO is "1-7-10" or "1/7/10" or "1.7.10" or "01-07-2010" or "01-07-2010" or "01.07.2010" when i put this value is automatic Convert in Date "01-07-2010"

can anybody help me about this issue

Thanks in Advance



Hitesh Patel


Hi All

i am Working on Text Value to Convert Automatic in Date

hear is my Value which put in Text Box i need to Convert This value to DATE

Ex. Value ONE is "1-7" or "1/7" or "1.7" or "01-07" or "01-07" or "01.07" when i put this value is automatic Convert in Date "01-07-2010"

Value TWO is "1-7-10" or "1/7/10" or "1.7.10" or "01-07-2010" or "01-07-2010" or "01.07.2010" when i put this value is automatic Convert in Date "01-07-2010"

can anybody help me about this issue

Thanks in Advance



Hitesh Patel
Is it possible to populate an AutoComplete text box property in code from an Access query.  If so, how do I go about it?

The auto completion function keeps trying to "correct" text i put in the toolbar's Find combo box. It happens both when typing and when copy/pasting text. I'm sure this is great for some people, but i usually copy/paste exactly what i'm looking for into the text box, which is then mangled by auto complete into something that i'm not looking for. For example, i'll copy the word "connection", then do a quick ctrl-v/enter in the Find text box and after it fails to find anything (or even worse, found the wrong thing) i'll realize it has helpfully "corrected" the term to "connectionLock."

I realize that i can do ctrl-v/backspace/return to get the results i want, but i don't know whether or not auto complete is going to kick in for the term i'm using until after i've pasted the term in, at which point i've already hit return by reflex. I'd like to just turn auto complete off for the find textbox completely.

I've checked Tools->Options->Environment->Find and Replace, but there don't seem to be any applicable options there. So how do i turn off auto complete in this case?

Auto complete function in text box is already built in for windows forms for visual studio 2010. But I couldn't find it for WPF form. So can anyone help me giving the idea and code how to do it. I have a list box whose items will be the suggestions for text box. I am using visual studio 2010 (visual basic) WPF form.

hi all,

i have created an infopath which have one request no. field and it will auto increment when click on add new item on sharepoint Document library

field contains (highest value of column request no. +1 )  when infopath will open in browser.

What i have done on this:i have create new data connection on sharepoint library and then pick document library then choose ID field and insert function in the field max(ID)+1.

help me




<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure