Create a tab for each row found in db - c#

I have a query that selects a table form my db and displays it on some labels, but if the query finds more the one data row it has to display each one of them in a different tab of the form, how can i archive this.
Code:
try
{
mycon.Open();
string querieslabels = "Select *From Alerts where State = #state && Lv =#lv";
oleDbCmd = new OleDbCommand(querieslabels, mycon);
oleDbCmd.Parameters.Add("#state", OleDbType.VarChar, 10).Value = "Open";
oleDbCmd.Parameters.Add("#lv", OleDbType.VarChar, 2).Value = "1";
OleDbDataReader read1;
read1 = oleDbCmd.ExecuteReader();
read1.Read();
state = read1[4].ToString();
if (state != "Closed")
{
lblNum.Text = read1[0].ToString();
lblpress.Text = read1[1].ToString();
txtDescription.Text = read1[2].ToString();
lblDate.Text = read1[3].ToString();
lblOk.Visible = false;
pictureBox2.Visible = false;
mycon.Close();
}
else
{
//Hides labels and other control's
MakeNotVisible();
MessageBox.Show("No alert found");
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
finally
{
mycon.Close();
}
}
What I'm trying to create is some alert system, if there is more than 1 alert it should display in a different tab. Can some one guide me to the solution for this, any help or suggestion is appreciated.
NOTE: I'm using Win Form.

You could create a UserControl, with code that can display one record from a DataTable. Then you can create TabPages and add one new UC to it for each of your rows. Take care not to add too many pages, say no more than 10-15!
Update I just noticed that you are using a DataReader, not a DataTable. No problem, the same solution will worke here, too: Use the added ShowReader method and call it like below..!
Here is an example:
public partial class DataForm : UserControl
{
public DataTable theTable { get; set; }
public DataForm()
{
InitializeComponent();
}
public int showTableRow(int rowIndex)
{
if (theTable == null) return -1;
if (theTable.Rows.Count < rowIndex) return -2;
DataRow row = theTable.Rows[rowIndex];
label1.Text = row[0].ToString();
label2.Text = row[1].ToString();
label3.Text = row[2].ToString();
return 0;
}
public void showReaderRow(OleDbDataReader DR)
{
label1.Text = DR[0].ToString();
label2.Text = DR[1].ToString();
label3.Text = DR[2].ToString();
}
}
For easier access we'll keep a List:
List<DataForm> theDataPages = new List<DataForm>();
Now we can add DataForm pages to the Tab control tabFormPages from the records in a DataTable; here I limit the number to 5:
for (int r = 0; r < DTL.Rows.Count && r < 5; r++)
{
TabPage page = new TabPage( (r+1).ToString("Record #0" ));
DataForm aForm = new DataForm();
aForm.theTable = DTL;
aForm.Parent = page;
aForm.showTableRow(r);
tabFormPages.TabPages.Add(page);
theDataPages.Add(aForm);
}
For use with a DataReader you could write a read loop like this:
while (DR.Read())
{
TabPage page = new TabPage("Alert #"
+ (tabFormPages.TabPages.Count+1).ToString());
DataForm aForm = new DataForm();
aForm.Parent = page;
aForm.showReaderRow(DR);
tabFormPages.TabPages.Add(page);
theDataPages.Add(aForm);
}
First you add the class to your project: Add - Add Usercontrol.
Now you can open it in the Designer and put in all Labels you need as well as the and put a the code. Also flesh out the showRow method to properly display your data in those Labels..
Now you can add such UCs to TabPages in your Tab like I did above.
If you are using a DataTable you can also make one page display a certain record by calling the showRow again:
theDataPages[0].showRow(DTL.Rows.Count - 1);
This will show the last record in the first TabPage.
If you really need to access field on that UC you can create public properties for those fields and access them like so:
public DataTable theTable { get; set; }
public Label Label1 { get; set; }
//..
public DataForm()
{
InitializeComponent();
Label1 = label1;
//..
}
Now you can access the field(s):
if (theDataPages[0].Label1.Text == "Hiho"
theDataPages[0].Label1.BackColor = Color.Green;

Are you using a WinForms application or a WebForms application? You might need an Accordion control (http://www.codeproject.com/Articles/416521/Easy-WinForms-Accordion-Control) or a Tab Control (http://www.c-sharpcorner.com/UploadFile/mahesh/C-Sharp-tabcontrol/) or something similar. You can dynamically create the tabs in them based on the number of rows in your result.

Related

Create buttons dynamically from code behind in ASP.NET

I'm quite new to ASP.NET and I need your help.
I'm programming on an application which should help to fix frequent issues. Users can click the displayed cases if it describes their problem. The application searches for more cases or displays a possible solution.
Now what I need for this is some code which creates the buttons dynamically. I googled some ideas and created some code, however I was not able to get it to work.
It works to create the first selection of buttons with the Default_Load method. Also the OnClick event (ButtonClick_System) works fine which means I get the next selection.
From here it starts messing around. The dynamic buttons created in ButtonClick_System don't have a working OnClick action.
Instead of proceeding with ButtonClick_Question (because of btn_system.Command += ButtonClick_Question; in ButtonClick_System) it seems like it just loads the homepage (maybe something wrong with Page_Load?).
The application should do ButtonClick_Question until no more datasets available in database.
I got the following code:
using System;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data;
using Oracle.DataAccess.Client;
namespace Application
{
public partial class _default : System.Web.UI.Page
{
// Variables
private string app_name = "Application";
// ----- Page_Load ----- //
protected void Page_Load(object sender, EventArgs e)
{
Default_Load();
Session["Application"] = app_name;
}
// ----- Methods ----- //
// Load homepage
public void Default_Load()
{
pnl_default.Visible = true;
pnl_content.Visible = false;
HtmlGenericControl html_default = new HtmlGenericControl();
html_default.TagName = "div";
string cmdString = "(...)";
DataTable dtSystems = OraQueryData(cmdString);
foreach (DataRow dtRow in dtSystems.Rows)
{
int system_id = Convert.ToInt32(dtRow["SYSTEM_ID"]);
string system_name = Convert.ToString(dtRow["SYSTEM_NAME"]);
var btn_system = new Button
{
ID = "btn_" + system_name,
Text = system_name,
CssClass = "sys_buttons"
};
btn_system.Command += ButtonClick_System;
btn_system.CommandArgument = Convert.ToString(system_id);
html_default.Controls.Add(btn_system);
}
plh_default.Controls.Clear();
plh_default.Controls.Add(html_default);
}
// Button OnClick Events
protected void ButtonClick_System(object sender, CommandEventArgs e)
{
pnl_default.Visible = false;
pnl_content.Visible = true;
HtmlGenericControl html_questions = new HtmlGenericControl();
html_questions.TagName = "div";
int system_id = Convert.ToInt32(e.CommandArgument);
string cmdString = "(...)";
DataTable dtQuestions = OraQueryData(cmdString);
foreach (DataRow dtRow in dtQuestions.Rows)
{
string question_id = Convert.ToString(dtRow["FRAGE_ID"]);
string question_text = Convert.ToString(dtRow["FRAGE_TEXT"]);
var btn_system = new Button
{
ID = "btn_question" + question_id,
Text = question_text,
CssClass = "quest_buttons"
};
btn_system.Command += ButtonClick_Question;
btn_system.CommandArgument = Convert.ToString(system_id);
html_questions.Controls.Add(btn_system);
}
plh_content.Controls.Clear();
plh_content.Controls.Add(html_questions);
}
protected void ButtonClick_Question(object sender, CommandEventArgs e)
{
pnl_default.Visible = false;
pnl_content.Visible = true;
HtmlGenericControl html_ChildQuestions = new HtmlGenericControl();
html_ChildQuestions.TagName = "div";
int parent_id = Convert.ToInt32(e.CommandArgument);
string cmdString = "(...)";
DataTable dtChildQuestions = OraQueryData(cmdString);
foreach (DataRow dtRow in dtChildQuestions.Rows)
{
string question_id = Convert.ToString(dtRow["FRAGE_ID"]);
string question_text = Convert.ToString(dtRow["FRAGE_TEXT"]);
var btn_system = new Button
{
ID = "btn_question" + question_id,
Text = question_text,
CssClass = "quest_buttons"
};
btn_system.Command += ButtonClick_Question;
btn_system.CommandArgument = question_id;
html_ChildQuestions.Controls.Add(btn_system);
}
plh_content.Controls.Clear();
plh_content.Controls.Add(html_ChildQuestions);
}
// ----- Oracle Data Query Methods ----- //
// Create and execute query on database
public static DataTable OraQueryData(string cmdString)
{
string conString = ConfigurationManager.AppSettings["Connection"];
OracleConnection oraCon = new OracleConnection(conString);
OracleCommand oraCmd = new OracleCommand(cmdString, oraCon);
OracleDataAdapter oraDtAd = new OracleDataAdapter(oraCmd.CommandText, oraCon);
DataTable dt = new DataTable();
oraCon.Open();
oraDtAd.Fill(dt);
oraCon.Close();
return dt;
}
}
}
If I've understood the issue correctly I think you're using the wrong controls for the wrong usages.
What I'd suggest you need to do is bind the collection of FAQ records to a repeater or some other data set display control. You can then have an event on the repeater which can handle which record ID has been clicked, post back with that value and refresh the collection of data from that (maybe in another repeater). Don't dynamically create buttons and bind events to them otherwise you will end up in a mess.
Hope this helps.

How do i add a previous and next button to datagridview

I am using Visual studio 2012 and have made a windows form application, for one of the forms I am using a datagridview which shows the information of a table from the SQL database.
I have made the form load information from the datagridview rows directly into a textbox automatically.
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM Stock", con);
DataTable DATA = new DataTable();
SDA.Fill(DATA);
dataGridView1.DataSource = DATA
txtStock3.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
Descriptioncombo2.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
txtprice2.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
The problem is that I need to add a previous button and a next button so that users can navigate through the datagridview rows and see the information in a textbox from each column of a datagridview row. I have looked at similar questions and have browsed through the internet to look for a solution to my problem but i can't seem to find a way which works with my code. Also could you tell me how to add a line of code which tells the user that there is no more rows to select if they click next through all rows of the database.
One way to provide navigation is by using a BindingNavigator where you can remove unnecessary buttons and for TextBox you can data binding.
Code responsible for loading data. Replace the console.writeline in the catch as you see fit e.g. write to a log file etc.
public class DataOperations
{
public DataTable LoadCustomers()
{
DataTable dtCustomers = new DataTable();
using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
string commandText = #"SELECT [Identfier], [CompanyName],[ContactName],[ContactTitle] FROM [NORTHWND1.MDF].[dbo].[Customers]";
using (SqlCommand cmd = new SqlCommand(commandText, cn))
{
try
{
cn.Open();
dtCustomers.Load(cmd.ExecuteReader());
dtCustomers.Columns["Identfier"].ColumnMapping = MappingType.Hidden;
dtCustomers.Columns["ContactTitle"].ColumnMapping = MappingType.Hidden;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
return dtCustomers;
}
}
On a form, one BindingNavigator, one dataGridView, one TextBox
DataOperations dataOps = new DataOperations();
BindingSource bsCustomers = new BindingSource();
bsCustomers.DataSource = dataOps.LoadCustomers();
dataGridView1.DataSource = bsCustomers;
bindingNavigator1.BindingSource = bsCustomers;
txtContactTitle.DataBindings.Add("Text", bsCustomers, "ContactTitle");
An alternate to the BindingNavigator is to make the BindingSource form level, private variable. Then in buttons call BindingSource.Move method e.g. bsCustomers.MoveFirst(). Of course there is MoveNext, MoveLast and MovePrevious too.
//first
int i = 0;
this.dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[dataGridView1.CurrentCell.ColumnIndex];
//prev
int prev = dataGridView1.CurrentRow.Index - 1;
if (prev >= 0)
{
this.dataGridView1.CurrentCell = dataGridView1.Rows[prev].Cells[dataGridView1.CurrentCell.ColumnIndex];
//MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
}
//next
int next = dataGridView1.CurrentRow.Index + 1;
if (next < dataGridView1.Rows.Count)
{
this.dataGridView1.CurrentCell = dataGridView1.Rows[next].Cells[dataGridView1.CurrentCell.ColumnIndex];
//MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
}
//last
int i = dataGridView1.Rows.Count - 1;
if (i < dataGridView1.Rows.Count)
{
this.dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[dataGridView1.CurrentCell.ColumnIndex];
//MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
}
As an alternate to Karen's solution, if you prefer/must go with buttons to navigate then you'll want to handle the CurrentCellChanged event as well as the following button Click events:
private void DataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
if (this.dataGridView1.CurrentRow != null)
{
txtStock3.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
Descriptioncombo2.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
txtprice2.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
this.prevButton.Enabled = this.dataGridView1.CurrentRow.Index > 0;
this.nextButton.Enabled = this.dataGridView1.CurrentRow.Index < this.dataGridView1.Rows.Count - 1;
}
}
private void PrevButton_Click(object sender, EventArgs e)
{
int prev = this.dataGridView1.CurrentRow.Index - 1;
this.dataGridView1.CurrentCell = this.dataGridView1.Rows[prev].Cells[this.dataGridView1.CurrentCell.ColumnIndex];
}
private void NextButton_Click(object sender, EventArgs e)
{
int next = this.dataGridView1.CurrentRow.Index + 1;
this.dataGridView1.CurrentCell = this.dataGridView1.Rows[next].Cells[this.dataGridView1.CurrentCell.ColumnIndex];
}
The CurrentCellChanged event will handle logic for if you can click Previous or Next. Their respective click events simply move the current cell backwards or forwards one row.
You configure the comulmns in the grid to be your matching types. Then after the query you bind the data to this gridView. You add two buttons where the "next" button will fetch the currentselectedrow of the grid, and set it's follower to be the selected one. previous will do the opposite. This is a small pain in the ass. I hate grids in WinForms. The last 4 years, since I did not see them, have been the happiest years of my lif

show Listview column wise and and on button click show same listview in rowwise

I have a task to complete.. i must populate a list view from database and show in column wise and on a button click show it in a row wise... i just completed populating list view from database. now how do i display it it column wise and row wise... please help me...
This is the code i have tried to populate the database...
public partial class DtposMDIParentSystem : Form
{
List<object[]> result = new List<object[]>();
public DtposMDIParentSystem()
{
InitializeComponent();
//create the database connection
OleDbConnection aConnection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AP_AE\Desktop\DTPOS_APP\DataBase\DtposDatabase.accdb;");
//create the command object and store the sql query
OleDbCommand aCommand = new OleDbCommand("SELECT * FROM Food", aConnection);
try
{
aConnection.Open();
//create the datareader object to connect to table
OleDbDataReader reader = aCommand.ExecuteReader();
int i = 0;
while (reader.Read())
{
result.Add(new Object[reader.FieldCount]);
reader.GetValues(result[i]);
}
reader.Close();
aConnection.Close();
}
catch (InvalidOperationException ex)
{
MessageBox.Show("Invalid Masseage = " + ex.Message);
}
}
private void cmdOlives_Click(object sender, EventArgs e)
{
if (result.Count > 0)
{
string temp = "";
for (int i = 0; i < result[1].Length; i++)
{
temp += result[1][i] + " ";
}
TableOrderListView.Items.Add(temp);
}
}
}
You can achieve something like that by switching between different view modes:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
listView1.View = View.Details;
listView1.HeaderStyle = ColumnHeaderStyle.None;
listView1.Columns[0].Width = listView1.ClientSize.Width - 25;
listView1.Height = 244;
}
else
{
listView1.View = View.List;
listView1.Columns[0].Width = 50;
listView1.Height = 44;
}
}
You need to add one Column for Details view to work!
Note that you will have to adapt the size of the Listview:
In Details mode it will need to be tall enough to show several items
In List mode it will have to to rather wide but must not be tall enough to show more than one item (plus the scrollbar)!
If instead you mean to switch rows and columns you will have to do that in your datasource!

textbox auto complete (Multi Line)

I am making a auto suggestion / complete textbox in C#, i followed below link, but text box isnt showing the suggestions
How to create autosuggest textbox in windows forms?
//-------- Get all distinct description -----------------------------
OleDbCommand command = new OleDbCommand(Queries.qry16, Connection);
OleDbDataReader reader = command.ExecuteReader();
//--------- Storing ------------------------------------
while (reader.Read())
{
namesCollection.Add(reader.GetValue(0).ToString());
}
//----------- Close after use ---------------------------------------
reader.Close();
//----------- Set the auto suggestion in description box ------------
descriptionBox.AutoCompleteMode = AutoCompleteMode.Suggest;
descriptionBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
descriptionBox.AutoCompleteCustomSource = namesCollection;
Here is my code , it is in load function of winform. And the nameCollection initializtion is in constructor... kindly please help to make it working.
I am editing my post rather then creating new... I have tried the my own code in single line textbox and it worked. Now i want the same in multi line... For research i googled more then 2 days trying different codes (one with intelli sense) but it didnt worked as auto suggestion available in textbox. Can any one give me suggestion to code the whole procedure to multi line.. Thank you.
AutoCompleteSource does not work on multiline TextBox controls.
Wich means you need to make it from scratch:
I would make a ListBox to display the content of your autocomplete:
var listBox = new ListBox();
Controls.Add(listBox);
You need eventhandling on your textbox however this is a bit crude, so i would rewrite it to stop the keyupevent at some point:
private void textBox_KeyUp(object sender, KeyEventArgs e)
{
var x = textBox.Left;
var y = textBox.Top + textBox.Height;
var width = textBox.Width + 20;
const int height = 40;
listBox.SetBounds(x, y, width, height );
listBox.KeyDown += listBox_SelectedIndexChanged;
List<string> localList = list.Where(z => z.StartsWith(textBox.Text)).ToList();
if(localList.Any() && !string.IsNullOrEmpty(textBox.Text))
{
listBox.DataSource = localList;
listBox.Show();
listBox.Focus();
}
}
Now all you need is a handler to set the text in your textBox:
void listBox_SelectedIndexChanged(object sender, KeyEventArgs e)
{
if(e.KeyValue == (decimal) Keys.Enter)
{
textBox2.Text = ((ListBox)sender).SelectedItem.ToString();
listBox.Hide();
}
}
Put in null checks where appropriate
You need to add a New Component class by 'Adding New Item'. and then write the code for that class and then add that component wherever required..
Try this code as it works in my case:
AutoCompleteStringCollection MyCollection = new AutoCompleteStringCollection();
while (reader.Read())
{
namesCollection.Add(reader.GetString(0));
}
reader.Close();
descriptionBox.AutoCompleteMode = AutoCompleteMode.Suggest;
descriptionBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
descriptionBox.AutoCompleteCustomSource = namesCollection;
con.Close();
Please check if the reader is getting the desired records..:)
Bit of confusion on the "auto-suggestion" since that is basically auto-complete without the permission from the user to "complete" the text. Nevertheless here are a couple of links you might find helpful:
http://docs.jquery.com/UI/Autocomplete
Autocomplete functionality on a textarea
AutoComplete extender for multi-line Textbox
Scroll down on link #2, a user suggested a jquery solution and compare with link #1. You may find a solution.
Third link is from asp forums, similar question like yours was also answered by a link. You might want to check that out.
Thismay help you solving problem ;
You can change table name. you can change the query to load listbox.
ListBox lbox;
private void IletisimBilgileriDoldur()
{
try
{
string strQuery= "Select adres From tblIletisimBilgileri Where adres <> '';";
veri = new OleDbCommand(strQuery,strConn);
veri.CommandType = CommandType.Text;
if (strConn.State == ConnectionState.Closed) strConn.Open();
oku = veri.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(oku);
oku.Close();
txtAdres.AutoCompleteCustomSource.Clear();
if (dt.Rows.Count >= 0)
{
lbox = new ListBox();
for (int count = 0; count < dt.Rows.Count; count++)
{
lbox.Items.Add(dt.Rows[count]["adres"].ToString());
}
}
txtAdres.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtAdres.AutoCompleteSource = AutoCompleteSource.CustomSource;
if (strConn.State == ConnectionState.Open) strConn.Close();
}
catch (Exception)
{
if (strConn.State == ConnectionState.Open) strConn.Close();
}
}
private void txtAdres_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
var x = txtAdres.Left;
var y = txtAdres.Top + txtAdres.Height;
var width = txtAdres.Width;
const int height = 120;
lbox.SetBounds(x, y, width, height);
lbox.KeyDown += lbox_SelectedIndexChanged;
lbox.DoubleClick += lbox_DoubleClick;
gbxAdres.Controls.Add(lbox);
lbox.BringToFront();
lbox.Show();
ActiveControl = txtAdres;
}
void lbox_DoubleClick(object sender, EventArgs e)
{
txtAdres.Text = ((ListBox)sender).SelectedItem.ToString();
lbox.Hide();
}

Skip to a database record in c#

Here is some background on what I have been following.
http://www.homeandlearn.co.uk/csharp/csharp_s12p9.html
That will go to the last or first record of the database. I want to skip to a record in the access database that the user wants by inputting the ID number in a textbox and then the correct row will get put in the textboxes.
I think I can use this code from the above website. I have implemented everything else from the website above.
Global variable
int inc = 0;
The navigate records that I will call in my Skip button later
private void NavigateRecords()
{
DataRow dRow = ds1.Tables["Laptops"].Rows[inc];
txtMaker.Text = ds1.Tables["Laptops"].Rows[inc].ItemArray.GetValue(1).ToString();
txtModel.Text = ds1.Tables["Laptops"].Rows[inc].ItemArray.GetValue(2).ToString();
txtPrice.Text = ds1.Tables["Laptops"].Rows[inc].ItemArray.GetValue(3).ToString();
txtBids.Text = ds1.Tables["Laptops"].Rows[inc].ItemArray.GetValue(4).ToString();
txtScreen.Text = ds1.Tables["Laptops"].Rows[inc].ItemArray.GetValue(5).ToString();
txtCPU.Text = ds1.Tables["Laptops"].Rows[inc].ItemArray.GetValue(6).ToString();
txtMemory.Text = ds1.Tables["Laptops"].Rows[inc].ItemArray.GetValue(7).ToString();
txtHD.Text = ds1.Tables["Laptops"].Rows[inc].ItemArray.GetValue(8).ToString();
picLaptops.Image = Image.FromFile(ds1.Tables["Laptops"].Rows[inc].ItemArray.GetValue(9).ToString());
}
My skip button so far...
private void btnSkip_Click(object sender, EventArgs e)
{
NavigateRecords();
}
It is hard for me to do this. I know what I want but lack the technical skill to do it. It is very frustrating. I have no idea what to do.
If someone can work it out and show me the code I can then understand it and use it elsewhere.
Here is an example of the next button to go to the next record if that helps.
private void btnNext_Click(object sender, EventArgs e)
{
if (inc != MaxRows - 1)
{
inc++;
NavigateRecords();
}
else
{
MessageBox.Show("You have reached the end of available items", "End of Available Items", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Use data binding, instead of assigning values manually to controls.
create a model class
public class MyClass
{
public string Maker { get; set; }
public double price { get; set; }
// and so on, for all your fields
}
Add a object data source for MyClass in the "Data Sources" explorer in Visual Studio.
Drag the fields form the Data Sources to your form. Visual Studio automatically add a BindingSource and a BindingNavigator to your form.
Assign your data to the BindingSource in the form:
this.bindingSource1.DataSource = myData;
Where myData is some enumeration of MyClass objects.
You can do this for database sources as well. But personally I prefer to have my data in classes. Is's easier to handle, than either manipulating DataSets or form fields directly.
Based on your description, I think this is what you want
void btnNext_Click(object sender, EventArgs e) {
int id = Int32.Parse(yourIdTextBox.Text);
DataRow row = ds1.Tables["Laptops"].Rows.OfType<DataRow>()
.SingleOrDefault(r => (int)r.ItemArray[your id index] == id);
if (row == null)
{
//user typed in invalid row id
} else
processRow(row);
}
void processRow(DataRow row){
txtMaker.Text = row.ItemArray.GetValue(1).ToString();
txtModel.Text = row.ItemArray.GetValue(2).ToString();
txtPrice.Text = row.ItemArray.GetValue(3).ToString();
txtBids.Text = row.ItemArray.GetValue(4).ToString();
txtScreen.Text = row.ItemArray.GetValue(5).ToString();
txtCPU.Text = row.ItemArray.GetValue(6).ToString();
txtMemory.Text = row.ItemArray.GetValue(7).ToString();
txtHD.Text = row.ItemArray.GetValue(8).ToString();
picLaptops.Image = Image.FromFile(row.ItemArray.GetValue(9).ToString());
}
Which would then simplify your NavigateRecors() method to
private void NavigateRecords()
{
DataRow dRow = ds1.Tables["Laptops"].Rows[inc];
processRow(dRow);
}

Categories

Resources