ASP.NET - AutoComplete TextBox when choose dropDownList Item - c#

everyone. I have a web service with all cars in company with data:
CarNumber and CarBrand.
I want, where I choose CarNumber from DropDownList, CarBrand autocomplete in textBox.
This is my Web controls declaration;
ddCarNumber = new DropDownList();
ddCarNumber.Items.Add("-- Choose Car Number --");
ddCarNumber.SelectedIndexChanged += new EventHandler(ddCarNumber_SelectedIndexChanged);
GetCars();
this.Controls.Add(ddCarNumber);
lblCarBrand.Text = "Car Brand";
txtCarBrand = new TextBox();
txtCarBrand.MaxLength = 255;
this.Controls.Add(txtCarBrand);
Whit this method i get CarNumbers from Web Service:
private void GetCars()
{
Service1SoapClient client = new Service1SoapClient();
UserDetails details = new UserDetails();
details.userName = "Weber";
details.password = "!Q2w#4r";
DataTable dt = client.GetCars(details);
foreach (DataRow row in dt.Rows)
{
ddCarNumber.Items.Add(row[0].ToString());
}
}
I want where i choose CarNumber from DropDown, TextBox autoComplete with CarBrand.

in Dropdown selectedIndex Change Event
ddCarNumber_SelectedIndexChanged
Write below code
this.Controls.findcontrol("txtCarBrand").Text = ddCarNumber.SelectedItem.Text/Value //Based on your Data DataTextField/DataValueField
Hope this helps.

This is : my ddCarNumber_SelectedIndexChanged Method, This is working, but problem is with Event, not refresh a page... When I push F5 is Okay...
void ddCarNumber_SelectedIndexChanged(object sender, EventArgs e)
{
Service1SoapClient client = new Service1SoapClient();
UserDetails details = new UserDetails();
details.userName = "Weber";
details.password = "!Q2w#4r";
DataTable dt = client.GetCars(details);
foreach (DataRow row in dt.Rows)
{
if (ddCarNumber.SelectedValue == Convert.ToString(row[0]))
{
txtCarBrand.Text = row[1].ToString();
}
}
}

Related

How to pass value from datagridview to textbox

I am currently working on a system. I have a datagridview with a contextmenu and an edit and delete button on it. I want to pass the value of the selected rows to a textbox when I click the edit on contextmenu.
I have successfully passed the value to the textbox but the only values that show are from the last inputted data to whatever row I click. I don't know how to get the id, can someone please help me fix my problem? :(
Here is my code:
private void BtnEdit_Click(object sender, EventArgs e)
{
frmAddEditStudent frm = new frmAddEditStudent(this);
cn.Open();
cm = new SqlCommand("SELECT s.studentID, s.studentNo, s.Lname, s.Fname, s.MI, s.gender, s.yearLevel, s.section, s.studImage, g.name, g.contactNo, g.address FROM Student s INNER JOIN Guardian g ON g.studentNo = s.studentNo WHERE g.studentNo = s.studentNo AND s.isActive = 'true' AND s.studentID = studentID", cn);
cm.Parameters.AddWithValue("studentID", lblID.Text);
for (int i = 0; i < guna2DataGridView1.Rows.Count; i += 1)
{
frm.btnSave.Enabled = false;
frm.lblTitle.Text = "Edit Student Details";
frm.lblID.Text = guna2DataGridView1.Rows[i].Cells[1].Value.ToString();
frm.txtStudentNo.Text = guna2DataGridView1.Rows[i].Cells[2].Value.ToString();
frm.txtLname.Text = guna2DataGridView1.Rows[i].Cells[3].Value.ToString();
frm.txtFname.Text = guna2DataGridView1.Rows[i].Cells[4].Value.ToString();
frm.txtMI.Text = guna2DataGridView1.Rows[i].Cells[5].Value.ToString();
frm.cboGradeLevel.Text = guna2DataGridView1.Rows[i].Cells[7].Value.ToString();
frm.cboSection.Text = guna2DataGridView1.Rows[i].Cells[8].Value.ToString();
frm.txtGuardianName.Text = guna2DataGridView1.Rows[i].Cells[9].Value.ToString();
frm.txtContactNo.Text = guna2DataGridView1.Rows[i].Cells[10].Value.ToString();
frm.txtAddress.Text = guna2DataGridView1.Rows[i].Cells[11].Value.ToString();
//Load Image
byte[] bytes = (byte[])guna2DataGridView1.Rows[i].Cells[12].Value;
MemoryStream ms = new MemoryStream(bytes);
frm.studImage.Image = Image.FromStream(ms);
//Retrieve gender value to radio button
if (guna2DataGridView1.Rows[i].Cells[6].Value.ToString() == "Male")
{
frm.rbMale.Checked = true;
}
else
{
frm.rbFemale.Checked = true;
}
}
cn.Close();
frm.ShowDialog();
It does not show up the data in the row that I selected, instead it only shows the last row in my database table.
You can get the current row or the selected rows from a datagridview in the following way (I think ID is cell with Index 1):
Console.WriteLine(guna2DataGridView1.CurrentRow.Cells[1].Value.ToString());
foreach (DataGridViewRow loRow in guna2DataGridView1.CurrentRow.SelectedRows)
{
Console.WriteLine(loRow.Cells[1].Value.ToString());
}
But you overwrite the form values in your loop every time.
It seems that your form can only display one row and not a collection.
And what about the command cm??

Pass value from boundfield of gridview to controller

I have 2 gridview look like this:
and 2 controller for those gridview:
Gridview Controller 1:
[DataObjectMethod(DataObjectMethodType.Select, false)]
public List<OutstandingOrderInfo> OrderInfo()
{
using (var context = new eToolsContext())
{
var data2 = from po in context.PurchaseOrders
where !po.Closed
select new OutstandingOrderInfo()
{
Order = po.PurchaseOrderID,
Date = po.OrderDate,
VendorName = po.Vendor.VendorName,
ContactPhone = po.Vendor.Phone
};
return data2.ToList();
}
}
GridView2 Controller
[DataObjectMethod(DataObjectMethodType.Select,false)]
public OrderDetail GetOrderDetail (int purchaseOrderID)
{
using (var context = new eToolsContext())
{
var data = from pod in context.PurchaseOrderDetails
where pod.PurchaseOrderID == purchaseOrderID
select new OrderDetail()
{
StockItemID = pod.StockItemID,
Description = pod.StockItem.Description,
QuantityOnOrder = pod.StockItem.QuantityOnOrder,
};
return data.FirstOrDefault();
}
}
I'm trying to pass the value of Order boundfield in Gridview1 to controller of Gridview 2 as the parameter whenever the ViewOrder link button is clicked.
But I received the error that the data I passed is null. What am I doing wrong?
Here is my code for handling the click event:
protected void GridView1_SelectedIndexChanged(object sender, GridViewSelectEventArgs e)
{
e.Cancel = true; // to prevent any other processing in the GridView's default Select handling
GridView sendingGridView = sender as GridView; // notice the safe casting
GridViewRow row = sendingGridView.Rows[e.NewSelectedIndex];
var orderID = row.FindControl("Order") as Label;
int puchaseOrderID = int.Parse(orderID.Text);
GetOrderDetail(puchaseOrderID);
}
private void GetOrderDetail(int purchaseOrderID)
{
var controller = new ReceivingController();
var data = controller.GetOrderDetail(purchaseOrderID);
GridView2.DataSource = data.OrderDetail;
GridView2.DataBind();
}

Dynamically creating a CheckBoxList

I am trying to create a dynamic menu with a title and group of checkboxes. So the output would be something like this: (pseudocode-ly)
Title 1
-checkbox1 -checkbox2 -checkbox3
Title 2
-checkbox1 -checkbox2 -checkbox3
I can get the Title back just fine, but my checkboxes are not. (See below)
Care
System.Web.UI.WebControls.CheckBoxList
Corporate & Enterprise Solutions
System.Web.UI.WebControls.CheckBoxList
I realize I am returning a DataSet, I just don't know how to handle it.
BusinessUnit bu = new BusinessUnit();
DataSet businessNames = bu.ListBusinessUnitNames();
ArrayList buNames = new ArrayList();
if (businessNames.Tables.Count > 0 && businessNames.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in businessNames.Tables[0].Rows)
{
buNames.Add(row["BSUN_NAME"].ToString());
}
}
int counter = 1;
foreach (string name in buNames)
{
Label lblName = new Label();
lblName.ID = "unitName_" + counter;
lblName.Text = name;
CheckBoxList chkBoxes = new CheckBoxList();
chkBoxes.ID = name + "Programs_" + counter;
foreach (string item in buNames)
{
DataSet buPrograms = bu.ListBusinessUnitPrograms(item);
foreach (DataRow row in buPrograms.Tables[0].Rows)
{
chkBoxes.DataTextField = row[0].ToString();
chkBoxes.Text = chkBoxes.DataTextField;
}
}
programs.InnerHtml += lblName.Text + chkBoxes;
counter++;
}
Here are the mechanics for doing it in code:
ListItem LI1 = new ListItem("aaa");
ListItem LI2 = new ListItem("bbb");
LI1.Selected = true;
LI2.Selected = false;
chkBoxes.Items.Add(LI1);
chkBoxes.Items.Add(LI2);
(Assuming you're using WebForms [aspx])
In your code example, the statement programs.InnerHtml += lblName.Text + chkBoxes; is appending the value of the default .ToString() implementation of the chkBoxes object. To actually add the checkboxes to the page, you will need some sort of container control (such as a Placeholder) on the page, and append your dynamically created control to the container's Controls collection via phPlaceholder.Controls.Add(chkBoxes)

How to add tooltip for Checkboxlist for each item in asp.net

<asp:CheckBoxList ID="ckl_EditRole" DataValueField="RoleName" runat="server">
</asp:CheckBoxList>
public void BindListBoxPermission(int field)
{
MySqlCommand command = new MySqlCommand();
DataSet ds = new DataSet();
int newOrgID = field;
string MysqlStatement = "SELECT RoleName from tbl_Role Where RoleID >1 order by RoleID desc";
MySqlParameter[] param = new MySqlParameter[0];
ds = server.ExecuteQuery(CommandType.Text, MysqlStatement, param);
ckl_EditRole.DataSource = ds;
ckl_EditRole.DataBind();
}
For each item tooltip is different, for admin tooltip is creates user and for users tooltip is creates message. How can I add tooltip for each item inside the check box
protected void Page_PreRender(object sender, EventArgs e)
{
foreach (ListItem item in ckl_EditRole.Items)
{
item.Attributes["title"] = GetRoleTooltip(item.Value);
}
}
private static string GetRoleTooltip(string p)
{
// here is your code to get appropriate tooltip message depending on role
}
Use the ToolTip property:
<asp:CheckBoxList ID="ckl_EditRole" DataValueField="RoleName" runat="server" ToolTip="Roles">
</asp:CheckBoxList>
Is this what you are asking?
If you want to update the ToolTip for each item then you need to treat them separately:
for (int i = 0; i < ckl_EditRole.Items.Count; i++)
ckl_EditRole.Items[i].Attributes["title"] = "custom Tooltip";
You can use PreRender event-- loop over the items (should be ListItems), and you can set an html attribute for title based on the values of the checkbox.
In cases where I want to have alot of control over the checkboxes, I might favor putting a checkbox in a repeater-- but that might not be necessary here.
You can write the following snippet of code on the page load method:
chkbox.Items[0].Attributes.Add("Title", "Admin");
chkbox.ToolTip = "Admin";
chkbox.Items[1].Attributes.Add("Title", "User");
chkbox.ToolTip = "User";
This is what I use, with more features, like making the ListItem look like a linkbutton.
protected void FormatPaskWeeksPerStudentRow(GridViewRow gvRow)
{
SqlDataSource sdsTETpastWeeks = (SqlDataSource)gvRow.FindControl("sdsTETpastWeeks");
sdsTETpastWeeks.SelectParameters["StudentID"].DefaultValue = hfStudentID.Value.ToString();
if (sdsTETpastWeeks != null)
{
CheckBoxList cbl1 = (CheckBoxList)gvRow.FindControl("listWeeksTracking");
if (cbl1 != null)
{
cbl1.DataBind();
foreach (ListItem litem in cbl1.Items)
{
//disable the checkbox for now
litem.Enabled = false;
//see if any of the past weeks (excluding this week) needs to be highlighted as a hyperlink to show past comments
//get the Tracking value. If set, then mark the checkbox as Selected or Checked
DataSourceSelectArguments dss = new DataSourceSelectArguments();
DataView dv = sdsTETpastWeeks.Select(dss) as DataView;
DataTable dt = dv.ToTable() as DataTable;
if (dt != null)
{
//this loops through ALL the weeks available to the student, for this block
//it tries to match it against the current ListItem for the week it's loading and determines if they match
//if so then mark the item selected (checked=true) if the value in the sub query says it's true
foreach (DataRow dr in dt.Rows)
{
if (litem.Text == dr.ItemArray[0].ToString() && litem.Text != ddlWeekNo.SelectedItem.Text)
{
if ((bool)dr.ItemArray[1])
litem.Selected = true;
//for those that were not ticked in prior weeks, make a ToolTip with the text/comment made in that week and underscore the week number
else
{
litem.Attributes["title"] = dr.ItemArray[2].ToString();
litem.Attributes.Add("style", "color:Blue;font-style:italic;text-decoration:underline;");
}
}
}
}
}
}
}
}
So in effect I am placing a ToolTip that's unique based on the data from the DatSource and I change the appearance of the ListItem to blue underline.

how to set SelectedIndex in DataGridViewComboBoxColumn?

i am using a datagridview in that i am using a datagridviewcomboboxcolumn, comboboxcolumn is displaying text but the problem is i want to select the first item of comboboxcolumn by default how can i do this
DataGridViewComboBoxColumn dgvcb = (DataGridViewComboBoxColumn)grvPackingList.Columns["PackingUnits"];
Globals.G_ProductUtility G_Utility = new Globals.G_ProductUtility();
G_Utility.addUnittoComboDGV(dgvcb);
DataSet _ds = iRawMaterialsRequest.SelectBMR(bmr_ID, branch_ID, "PACKING");
grvPackingList.DataSource = _ds.Tables[0];
int i = 0;
foreach (DataRow dgvr in _ds.Tables[0].Rows)
{
grvPackingList.Rows[i].Cells["Units"].Value = dgvr["Units"].ToString();
i++;
}
The values available in the combobox can be accessed via items property
row.Cells[col.Name].Value = (row.Cells[col.Name] as DataGridViewComboBoxCell).Items[0];
the best way to set the value of a datagridViewComboBoxCell is:
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item1", "0");
dt.Rows.Add("Item1", "1");
dt.Rows.Add("Item1", "2");
dt.Rows.Add("Item1", "3");
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.DefaultCellStyle.Font = new Font("Tahoma", 8, FontStyle.Bold);
cmb.DefaultCellStyle.ForeColor = Color.BlueViolet;
cmb.FlatStyle = FlatStyle.Flat;
cmb.Name = "ComboColumnSample";
cmb.HeaderText = "ComboColumnSample";
cmb.DisplayMember = "Item";
cmb.ValueMember = "Value";
DatagridView dvg=new DataGridView();
dvg.Columns.Add(cmb);
cmb.DataSource = dt;
for (int i = 0; i < dvg.Rows.Count; i++)
{
dvg.Rows[i].Cells["ComboColumnSample"].Value = (cmb.Items[0] as
DataRowView).Row[1].ToString();
}
It worked with me very well
If I had known about doing it in this event, it would have saved me days of digging and
trial and errors trying to get it to set to the correct index inside the CellEnter event.
Setting the index of the DataGridViewComboBox is the solution I have been looking for.....THANKS!!!
In reviewing all the issues other coders have been experiencing with trying to set
the index inside of a DataGridViewComboBoxCell and also after looking over your code,
all that anyone really needs is:
1. Establish the event method to be used for the "EditingControlShowing" event.
2. Define the method whereby it will:
a. Cast the event control to a ComboBox.
b. set the "SelectedIndex" to the value you want.
In this example I simply set it to "0", but you'd probably want to apply so real life logic here.
Here's the code I used:
private void InitEvents()
{
dgv4.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler( dgv4EditingControlShowing );
}
private void dgv4EditingControlShowing( object sender, DataGridViewEditingControlShowingEventArgs e )
{
ComboBox ocmb = e.Control as ComboBox;
if ( ocmb != null )
{
ocmb.SelectedIndex = 0;
}
}
If DataGridViewComboBoxCell already exist:
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item 1", "0");
dt.Rows.Add("Item 2", "1");
dt.Rows.Add("Item 3", "2");
dt.Rows.Add("Item 4", "3");
for (int i = 0; i < dvg.Rows.Count; i++)
{
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dvg.Rows[i].Cells[1];
comboCell.DisplayMember = "Item";
comboCell.ValueMember = "Value";
comboCell.DataSource = dt;
};
I've had some real trouble with ComboBoxes in DataGridViews and did not find an elegant way to select the first value. However, here is what I ended up with:
public static void InitDGVComboBoxColumn<T>(DataGridViewComboBoxCell cbx, List<T> dataSource, String displayMember, String valueMember)
{
cbx.DisplayMember = displayMember;
cbx.ValueMember = valueMember;
cbx.DataSource = dataSource;
if (cbx.Value == null)
{
if(dataSource.Count > 0)
{
T m = (T)cbx.Items[0];
FieldInfo fi = m.GetType().GetField(valueMember, BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
cbx.Value = fi.GetValue(m);
}
}
}
It basically sets the .Display and .ValueMember properties of the DataGridViewComboBoxCell and uses a List as DataSource. It then takes the first item, and uses reflection to get the value of the member that was used as ValueMember and sets the selected value via .Value
Use it like this:
public class Customer
{
private String name;
public String Name
{
get {return this.name; }
set {this.name = value; }
}
private int id;
public int Id
{
get {return this.id; }
set {this.id = value; }
}
}
public class CustomerCbx
{
private String display;
public String Display
{
get {return this.display; }
set {this.display = value; }
}
private Customer value;
public Customer Value
{
get {return this.value; }
set {this.value = value; }
}
}
public class Form{
private void Form_OnLoad(object sender, EventArgs e)
{
//init first row in the dgv
if (this.dgv.RowCount > 0)
{
DataGridViewRow row = this.dgv.Rows[0];
DataGridViewComboBoxCell cbx = (DataGridViewComboBoxCell)row.Cells[0];
Customer c1 = new Customer(){ Name = "Max Muster", ID=1 };
Customer c2 = new Customer(){ Name = "Peter Parker", ID=2 };
List<CustomerCbx> custList = new List<CustomerCbx>()
{
new CustomerCbx{ Display = c1.Name, Value = c1},
new CustomerCbx{ Display = c2.Name, Value = c2},
}
InitDGVComboBoxColumn<CustomerCbx>(cbx, custList, "display", "value");
}
}
}
}
It seems pretty hacky to me, but I couldn't find any better way so far (that also works with complex objects other than just Strings). Hope that will save the search for some others ;)
You need to set the Items for the new cell. This must be auto done by the column when creating a new row from the UI.
var cell = new DataGridViewComboBoxCell() { Value = "SomeText" };
cell.Items.AddRange(new String[]{"SomeText", "Abcd", "123"});
something different worked for me what i did is to simply set the value of dtataGridComboBox when ever new record is added bu user with 'userAddedRow' event. For the first row I used the code in constructor.
public partial class pt_drug : PatientDatabase1_3._5.basic_templet
{
public pt_drug()
{
InitializeComponent();
dataGridView_drugsDM.Rows[0].Cells[0].Value = "Tablet";
}
private void dataGridView_drugsDM_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
dataGridView_drugsDM.Rows[dataGridView_drugsDM.RowCount - 1].Cells[0].Value = "Tablet";
}
}
Here the solution I have found : select the cell you are interested in so you can cast it to a combobox.
this.Invoke((MethodInvoker)delegate
{
this.dataGridView1.CurrentCell = dataGridView1.Rows[yourRowindex].Cells[yourColumnIndex];
this.dataGridView1.BeginEdit(true);
ComboBox comboBox = (ComboBox)this.dataGridView1.EditingControl;
comboBox.SelectedIndex += 1;
});

Categories