26 June 2012

Infopath Fill Dropdown Dyanamically ( at run time)

Hi All,
Some time you need to fill Drop-Down List Box of InfoPath runtime from database or webservice.
here is solution and demo code will help you to solve this purpose. this solution is best when you are trying to bind small amount of data to drop-down.
here I have taken Customer drop-down and it will fill runtime from Repeating table.

Here in image you can see we have Customer drop-down and below it one Repeating table.
  1. Open InfoPath.
  2. Click on design new template.
  3. drag dropdown on the InfoPath Form and give name "Customer"
  4. drag repeating table on InfoPath form.
  5. now go to the data source pane and rename the binding shown in the figure.
  6. Now, double click on customer Drop-down, In Data tab List box entry section select radio button “lookup value in the Form’s data source”.
  7. In Entries select “tblCustomer”
  8. Value : myValue , Text: myText.
  9. And then Hide Repeating table from Conditional Formation in Display tab.
  10. Download the Code (Click Here)
  11. Here is Main Code


private void fillDropDown(string table, string tr, string DropDownName)
{
string value, Text;
value = string.Empty;
Text = string.Empty;
DataTable dt = null;
//if you have more than one Dropdown you can use switch case
switch (DropDownName)
{
case "Customer":
//here you can use webservice to fill dropdown..
dt = this.CustomerDataSource();
value = "//my:Value";
Text = "//my:Text";
break;
}
XPathNavigator root = this.MainDataSource.CreateNavigator();
XPathNavigator row = root.SelectSingleNode("//my:" + tr + "[1]", NamespaceManager);
// make a copy of the node by cloning it
XPathNavigator row1;
if (dt != null)
{
foreach (System.Data.DataRow dr in dt.Rows)
{
// set the new values of the row’s fields
row1 = row.Clone();
row1.SelectSingleNode(value, NamespaceManager).InnerXml =Convert.ToString(dr["Value"]);
row1.SelectSingleNode(Text, NamespaceManager).InnerXml = Convert.ToString(dr["Text"]).Replace("&", " "); ;
XPathNavigator parent = row1.SelectSingleNode("//my:" + table, NamespaceManager);
parent.AppendChild(row1);
}
row.DeleteSelf();
}
}