I've got a query to display parts by serial numbers in one column and the number of processes they went through in the other column.
This data is dumped into a GridView control called gvSummary. It works OK now.
What I'd like to do is add a second GridView control called gvDetails next to gvSummary, and replace all of the data in gvSummary with a control that will run a detail query for that particular part when it is clicked.
My plan of attack is to replace the text in the Serial_Number column (Column[0]) with something like the HyperLink control, where the NavigateUrl specifies to call my GetDetails method by passing the text of the Serial_Number.
var table = GetPartsForTimePeriod();
for (int i = 0; i < table.Rows.Count; i++) {
string serialNumber = table.Rows[i][0].ToString().Trim();
var link = new HyperLink()
{
ID = string.Format("lnk{0}", serialNumber.Replace(' ', '_'))
};
link.Text = serialNumber;
link.NavigateUrl = string.Format("GetDetails(\"{0}\"}", serialNumber);
table.Rows[i][0] = link;
}
GridView1.DataSource = table;
GridView1.DataBind();
Issues:
A HyperLink would require a page to load, and all I really want to do is fill this next query into the gvDetails control.
What is the right way to go about this? I generally code WinForms, and I can't think of the way to do this in ASP.NET.
Related
On the page, I have only textbox,button,gridview and a label.
I write username to textbox and click button, so it searches in db and fills gridview and update label text as "xx result found" so xx is the count of results found in db.
the sample code is very short and easy:
string userName = TextBox2.Text;
SqlDataSource1.SelectCommand = "Select * From SampleTable Where name = '"+userName+"'";
ResultLable.Text = GridView1.Rows.Count + " Result Found";
GridView1.Visible = true;
ResultLable.Visible = true;
for example; there is a username John in db but Mary does not exist. When I search John, the count is 1 (which is correct), then I search for Mary and click button again still the number is 1(which is incorrect) but when I click button again it becomes 0. Same case valid for reverse scenario as well.
So the problem is click button is not updating the number in first click-just working for 2nd click.
Why does it happen ?
after set SelectCommand you need to call
SqlDataSource1.DataBind();
GridView1.DataBind();
The problem is that you are looking in the GridView1.Rows.Count, when you click the button the Grid is not rebind so the Rows.Count will be from previous value of the grid.
ResultLable.Text = GridView1.Rows.Count + " Result Found";
You should Rebind your Grid before taking GridView1.Rows.Count() in the Button_Click.
Need to know: I am working with Windows Forms in Visual Studio and C#.
I have 5 comobobox's that I populate from SQL with the parts available in the DB. Part of the coding to it, one uses a DataTable and set the DataSource of the comboBox to that DataTable.
In this same DataTable via my SQL query, I have listed the cost of the part in the list. What I want to do is whichever part you pick from the dropdown list, the related price must show in the textbox next to it.
I am trying to use the comboBox1_SelectedIndexChanged for this, but the problem I run into is as soon as the DataSource gets set to the DataTable while the form's initial loading, it gets picked up as a Index change and the comboBox1_SelectedIndexChanged wants to run. But at this point in time, the SelectedIndex Value is null due to it still loading, causing it to give me a exception cast error.
how can I work around this?
DataTable SparePart = new DataTable() is declared outside the function to make it available as "public" so that the comboBox1_SelectedIndexChanged can access it.
Then I have this code to populate the comboBox:
//Read Status info from DB
SqlDataAdapter SparePartReader = new SqlDataAdapter(SQLSparePartDropbox);
SparePartReader.Fill(SparePart);
comboBoxFinJCSpares1.DataSource = SparePart;
comboBoxFinJCSpares1.DisplayMember = "DisplayMember";
comboBoxFinJCSpares1.ValueMember = "PartID";
//Set Combox1 affiliated Cost value to cost textbox
int ComBo1PartID = (int)comboBoxFinJCSpares1.SelectedValue;
string CostPrice = (from DataRow dr in SparePart.Rows
where (int)dr["PartID"] == ComBo1PartID
select (string)dr["PartCost"]).FirstOrDefault();
textBoxFinJCCost1.Text = CostPrice.ToString();
and then I have this for the comboBoxFinJCSpares1_SelectedIndexChanged:
//Set Combox1 affiliated Cost value to cost textbox
int ComBo1PartID = (int)comboBoxFinJCSpares1.SelectedValue;
string CostPrice = (from DataRow dr in SparePart.Rows
where (int)dr["PartID"] == ComBo1PartID
select (string)dr["PartCost"]).FirstOrDefault();
textBoxFinJCCost1.Text = CostPrice.ToString();
enter image description here
The solution is as easy as making one boolean variable and call it formLoaded.
Set it to false, then set it to true after the form loads.
Put your code for populating combobox inside if statement and that should do it
Cheers ~ ChenChi
demo:
//Read Status info from DB
if(formLoaded)
{
SqlDataAdapter SparePartReader = new SqlDataAdapter(SQLSparePartDropbox);
SparePartReader.Fill(SparePart);
comboBoxFinJCSpares1.DataSource = SparePart;
comboBoxFinJCSpares1.DisplayMember = "DisplayMember";
comboBoxFinJCSpares1.ValueMember = "PartID";
//Set Combox1 affiliated Cost value to cost textbox
int ComBo1PartID = (int)comboBoxFinJCSpares1.SelectedValue;
string CostPrice = (from DataRow dr in SparePart.Rows
where (int)dr["PartID"] == ComBo1PartID
select (string)dr["PartCost"]).FirstOrDefault();
textBoxFinJCCost1.Text = CostPrice.ToString();
}
Thanks guys, the "SelectedChangeCommitted" option suggested by Marcel Hoekstra solved my problem.
I would like to search my DataSet for a customer name, this name will occur more than once throughout the dataset, meaning there will be more than 1 result (multiple rows returned)
When my search button is clicked, form2 opens up, and in theory should display all rows containing the customer name, but how do I achive this?
I can get it to display 1 row without a problem, but how would I make it display all rows, and the data in textboxes.
At the moment I am using a foreach loop to fill text boxes with returned data, but this only takes data from 1 row within my DataSet.
Is there a way I can make my form auto generate textboxes and populate them will all the data from the array? When I run my query at the moment, it fills the textboxes on form2 with the last rotation of the foreach.
DB Sample
Appreciate any help
Adam
DataRow[] returnedRows;
returnedRows = ds.Tables["Table_Data_1"].Select("cust_name='" + searchFor + "'");
foreach (DataRow returned in returnedRows)
{
tbName.Text = returned[1].ToString();
tbAddress.Text = returned[2].ToString();
tbPhone.Text = returned[3].ToString();
tbMake.Text = returned[4].ToString();
tbModel.Text = returned[5].ToString();
tbReg.Text = returned[6].ToString();
tbYear.Text = returned[7].ToString();
tbParts1.Text = returned[8].ToString();
tbParts2.Text = returned[9].ToString();
tbParts3.Text = returned[10].ToString();
tbParts3.Text = returned[11].ToString();
}
The reason you're having just a single value appear is that you're setting the text of your text boxes to a new value for each row that you've selected. You could change your code to instead add to the Text in the the Textboxes:
tbName.Text += returned[1].ToString() + Environment.NewLine;
Or you could instead bind it to a DataGridView, which is designed to display tabular data. Assuming the DataGridView was named something like customerDataView,
returnedRows = ds.Tables["Table_Data_1"].Select("cust_name='" + searchFor + "'");
var newTable = returnedRows.CopyToDataTable();
BindingSource bindSource = new BindingSource();
bindSource.DataSource = newTable;
var customerDataView.DataSource = bindSource;
You can generate textboxes dinamicaly
Its something like this
foreach (DataRow returned in returnedRows)
{
TextBox txt = new TextBox();
txt.ID = "textBox1"; //generate id dinamically can be a count
txt.Text = returned[1].ToString();
form1.Controls.Add(txt);
}
The way you've implemented the loop override the data in each interation
I've improved the sample code from following this post
https://stackoverflow.com/a/2229040/5252904 answer provided by #rahul.
I am trying to import csv to mssql using c# code on a asp.net application.
the below c# code helps to load the csv file, choose the table to import to
and then a button click event matches columns and populates a gridview (dgvmatchdata)
the gridview has two columns where the left side column lists all the available table headers from db
and right side column lists all the csv headers in a drop down list.
now, there are 3 conditions
1. both table and csv has equal no. of column headers.
2. table has more columns than csv
3. csv has more columns than table.
i have successfully finished the first two scenarios. and now, i am stuck at the 3rd scenario
my approach to this is,
for example lets consider the table as 10 columns and csv has 15 columns.
i wish to create 15 rows in dgvmatchdata and display the 10 table column headers on the left side
on their own labels for each. the equivalent righ side of the dgvmatchdata will have a drop down list
which contains 'ignore this column' + 15 columns headers from the csv. so, the ddl will now have 16 items.
i want to place text box for the remaining 5 rows on the table column side and i want to populate
the text box with dropdown list. selected items.text during dropdown selected item change event.
now after i have successfully got text inside the remaining 5 text boxes i will write a code on a button click event
to alter table in the db and then the next step would simply import the csv data to the altered table flawlessly.
the point where i am seeking help is, i have placed the text box correctly but the text box disappears on ddl.selecteditem changed
due to post back issue and i am unable to get the text inside the text box.
kindly help.
Gridview Code
protected void dgvmatchdata_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataTable dt = (DataTable)Session["importcsv"];
string[] csvcolNames = (from dc in dt.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();
string tablename = ddltable2.SelectedItem.Text;
string[] dbcolNames = loadDataBaseColumns(tablename);
int dbcol = dbcolNames.Length;
int csvcol = csvcolNames.Length;
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlcsvcolumns = (e.Row.FindControl("ddlcsvcolumns") as DropDownList);
ddlcsvcolumns.DataSource = csvcolNames;
ddlcsvcolumns.DataBind();
ddlcsvcolumns.Items.Insert(0, new ListItem("Please select"));
}
for (int i = 0; i < dgvmatchdata.Rows.Count; i++)
{
DropDownList ddlselect = dgvmatchdata.Rows[i].FindControl("ddlcsvcolumns") as DropDownList;
foreach (string col in csvcolNames)
{
string tablcol = ((Label)dgvmatchdata.Rows[i].FindControl("lblcolumns1")).Text;
if (tablcol == col)
{
ddlselect.SelectedItem.Text = col;
ddlselect.Enabled = false;
dgvmatchdata.Rows[i].Cells[1].BackColor = System.Drawing.Color.SpringGreen;
}
}
}
}
Drop Down Selected Index Changed
protected void ddlcsvcolumns_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < dgvmatchdata.Rows.Count; i++)
{
string selectcolumns = ((DropDownList)dgvmatchdata.Rows[i].FindControl("ddlcsvcolumns")).SelectedItem.Text;
Label selectlabel = (dgvmatchdata.Rows[i].FindControl("lblColumns") as Label);
TextBox txtcol = (TextBox)dgvmatchdata.Rows[i].FindControl("txtDynamicText" + i.ToString());
if (selectcolumns.Equals("Please select"))
{
selectlabel.Text = "";
}
else
{
selectlabel.Text = selectcolumns;
}
}
}
I know how to to do it and put the data on textbox when I select a row from a gridview, What I want to achieve now is when I open a modal pop up form containing a gridview, it will automatically select or extract the date column from the last row of gridview.
This is for the purpose of determining the last date from the record.
Here's what I got so far (under click event for button "ADD")
if (grdSpecificTenantRental.Rows.Count == 0)
{
txtdatefrom.Text = "No record yet";
}
else
{
GridViewRow rowtwo = grdSpecificTenantRental.Rows[grdSpecificTenantRental.Rows.Count - 1];
string index = rowtwo.Cells.ToString();
txtdatefrom.Text = index;
}
Here's the output int he textbox: System.Web.UI.WebControls.TableCellCollection
Obviously this line is incorrect: string index = rowtwo.Cells.ToString();
I want to extract the 4th column in the last row which is the end date
Currently you are getting all the cells that is CellCollection so if you want to get perticular column value then use that array's index to get the required columns value.As you mentioned 4th columns so use the index 3 because index starts from 0.You might want to access it like this,
txtDateFrom.Text = grdSpecificTenantRental.Rows[grdSpecificTenantRental.Rows.Count - 1].Cells[3].Text;