Csharp database application using Access Database - c#

I'm new to programming, and trying to develop a database application with C# 2010 Express using MS Access DB 2010.
I've DataGridView and Detail view generated thru wizard on the form. I'm filtering the data with TextChanged event of a textbox.
When I navigate records, datagridview also scrolls according to current record on Detail view, and vice versa.
After filtering applied and removed this navigation behavior does not work at all (i.e. datagridview does not scroll according to current record in detail view anymore).
Any help would be appreciated.
Thanks.
Here is the code I use for filtering data (FilterField comes from Tag properties of radio buttons):
DataView dv = new DataView(personel_csDataSet.Tables["tblData"]);
dv.RowFilter = FilterField + " like '%' + '" + tbFilter.Text + "' + '%' ";
this.tblDataDataGridView.DataSource = dv;
tblDataBindingSource.Filter = FilterField + " like '%' + '" + tbFilter.Text + "' + '%' ";

That's because you set a different data source to the grid and the details view. If tblDataBindingSource is the data source of the detail view, assign it as a data source of the grid and don't create another view:
this.tblDataDataGridView.DataSource = tblDataBindingSource;
tblDataBindingSource.Filter = FilterField + " like '%' + '" + tbFilter.Text + "' + '%' ";
BTW, you don't have to assign the data source exactly there. You can do it in the beginning and you don't have to reassign it after applying a filter.

Related

How to display data into table and graph of crystal report

Actually, I am trying to display the data into a crystal report table and on graph. so please tell me if I have created one xyz.rpt file and create one table and graph structure inside this report. How to use these structures multiple times in my report. Suppose I have a student table and this table contains data of multiple class for example I have two classes data class 8 and class 9. In this situation all the data of the both class are displaying in a single table and single graph. but I am trying to display the class 8 data into a table after that my table terminates here and display graph for class 8 after that in second loop class 8 display in another table which comes after the first graph with the help of same table structure and then display the graph for this class.
Here is my code, Which display all data into single table and single graph..
dtoverall = DbClass.getdata(CommandType.Text, "select vn.VelocityNormalX VNX,vn.VelocityNormalY VNY,vn.VelocityNormalZ VNZ,vn.Unit VNU, vn.SampleTimeVN VNT,an.AccelerationNormalX ANX,an.AccelerationNormalY ANY,an.AccelerationNormalZ ANZ,an.Unit ANU from vel_normal_overall vn left join acc_normal_overall an on vn.SampleTimeVN = an.SampleTimeAN where vn.SampleTimeVN between '" + SubTime + "' and '" + CurrTime + "' and vn.sensorid = '" + SensorNo + "'");
if (dtoverall.Rows.Count > 0)
{
foreach (DataRow drtime in dtoverall.Rows)
{
convertedtime = timechange.IndianTime(Convert.ToString(drtime["VNT"]));
string loc = FName + "/" + AName + "/" + TName + "/" + MName + "/" + PName;
Overallall.Rows.Add(convertedtime, Convert.ToString(Math.Round(Convert.ToDouble(drtime["VNX"]),3))+Convert.ToString(drtime["VNU"]), Convert.ToString(Math.Round(Convert.ToDouble(drtime["VNY"]), 3)) + Convert.ToString(drtime["VNU"]), Convert.ToString(Math.Round(Convert.ToDouble(drtime["VNZ"]), 3)) + Convert.ToString(drtime["VNU"]), Convert.ToString(Math.Round(Convert.ToDouble(drtime["ANX"]), 3)) + Convert.ToString(drtime["ANU"]), Convert.ToString(Math.Round(Convert.ToDouble(drtime["ANX"]), 3)) + Convert.ToString(drtime["ANU"]), Convert.ToString(Math.Round(Convert.ToDouble(drtime["ANX"]), 3)) + Convert.ToString(drtime["ANU"]), loc);
}
}
crptall.Database.Tables["OverallForAll"].SetDataSource(Overallall);
CrysRptViewer.ReportSource = crptall;
CrysRptViewer.Refresh();
Group the report by {Class}. You do this by using the menu option of Insert, Group... or by using Report, Group Expert...
Then, place the chart in the Group Footer section.

How can I insert data from a text field into a foreign key in the database

How can I insert data from a text field into a foreign key in the database. Basically, I have tables named Employee and Role, RoleId is a foreign key in Employee, but the role text field is a string.
I have this
String Query = "insert into EMPLOYEE (LastName,FirstName,Manager,RoleId,HireStatus) values('" + this.txtLName.Text + "','" + this.txtFName.Text + "','" + this.txtManager.Text + "','" + this.txtRoleId.Text + "','" + this.txtHireStatus.Text + "');";
Edited - I have this, but I cannot have select with the following string
string Query = "insert into EMPLOYEE(LastName,FirstName,RoleId,Manager,HireStatus) values('" + this.txtLName.Text + "','" + this.txtFName.Text + "','" + ( SELECT RoleId From Role WHERE Role.RoleId = this.txtRole.Text ) + "','" + this.txtManager.Text + "','" + this.cmbHireStatus.Text + "');";
I think you should do this:
String Query = "insert into EMPLOYEE (LastName,FirstName,Manager,RoleId,HireStatus) values('" + this.txtLName.Text + "','" + this.txtFName.Text + "','" + this.txtManager.Text + "','" + this.txtRoleId.Text + "','" + this.txtHireStatus.Text + "');";
If you are trying to add a new Employee assigned to an existing role, then a better design would be have a dropdown with all Roles populated instead of a textbox for user to enter.
The dropdown should get filled with all the Roles from Roles table. (map the SelectedValue attribute of the dropdown to - RoleId and SelectedText to RoleName).
When you submit the form, you will get the SelectedValue (RoleId) which you can directly send as part of the INSERT statement, i.e., dropDownRole.SelectedValue instead of txtRoleId.Text
Note: Your insert query seems to be a classic candidate for SQL Injection. I suggest you transform it to Parameterized query.
Update: Now that I came to know it is a Winforms application, adding more detailed snippets. Here is how you can do it in the Win Forms world (not as intuitive as web app world though :) ) and please bear with me, it has been years since I had written a winforms snippet.
Define your dropdown combo box like this -
cbxRole.DataSource = roles; // data from back end
cbxRole.Name = "Role";
cbxRole.DropDownStyle = ComboBoxStyle.DropDownList;
cbxRole.DisplayMember = "RoleName"; // should match the property name in your roles data table
cbxRole.ValueMember = "RoleId"; // should match the property name in your roles data table
cbxRole.SelectedItem = null;
cbxRole.SelectedText = "Select Role";
Observe the ValueMember and DisplayMember properties. DisplayMember tells what property in the roles data source to be used to display as the dropdown item text. ValueMember specifies the property to be used to identify each of the item behind the scenes.
When you submit the details, access the SelectedValue property to get the RoleId corresponding to the selected role name.
private void btnCreate_Click(object sender, EventArgs e)
{
var firstName = txtFirstName.Text;
var lastName = txtLastName.Text;
var roleId = (int)cbxRole.SelectedValue;
}
The SelectedValue property fetches the value of the column identified by the ValueMember property in the dropdown definition, which is the RoleId value. Now, you can send this 'roleId' variable's value to the insert query.
here is how it looks like when you submit -
here is quick sample UI -

programming for keyword search from database?

Hello I have a table with following columns.
Profile_ID,
Name,
Age,
More_Info_about family,
qualification details,
job details and
partner_preference
I have to search on keyword basis and keyword is to be taken from textbox.
The search result should be in such a way so that if keyword presents in starting, ending and in between the sentence of any of the columns presents in where conditions.
I tried LIKE '" + txtbox_keyword.Text + "'
but is not working properly it is not searching data if keyowrd is present in between sentense.
select (Profile_ID,Name,Age, More_info_about_family,Job_Business_Location_City,Salary
from tblRegistration
WHERE More_info_about_family LIKE '" + txtbox_keyword.Text + "'
OR LIKE '" + txtbox_keyword.Text + "'
OR origin LIKE '" + txtbox_keyword.Text + "'
OR Job_Detail LIKE '" + txtbox_keyword.Text + "' ", con);
Use sqlParameter for except sql injection and you need add %% in your query to search by field.
SqlParameter parameter = new SqlParameter("#keyWord",txtbox_keyword.Text);
select (Profile_ID,Name,Age, More_info_about_family,Job_Business_Location_City,Salary
from tblRegistration
WHERE More_info_about_family LIKE '%#keyWord%'
OR LIKE '%#keyWord%'
OR origin LIKE '%#keyWord%'
OR Job_Detail LIKE '%#keyWord%', con,parameter);

look up value from another sql table in c# winforms

I am using c# winform, When the users input something in State field I want to look up that value in another table and find that code. I have commented the line below on what I have tried but that has not worked
MySqlCommand cmdDatabase = new MySqlCommand(" update `STUDENT REGISTER` INNER JOIN `States` ON `STUDENT REGISTER`.`State` = `States`.`State Code` set " +
"`first Name`='" + cboStudentFirstName.Text.Trim() + "'," +
"`Surname`='" + cboStudentSurname.Text.Trim() + "'," +
//if the person selects inputs VIC on this table I want it to look up that value in a table called states and bring me back the code for that state
"STUDENT REGISTER.State= States.State Code," +

Question about adding to database from text entered into textbox

I have an app that displays data from a sql database in a datagrid. I am adding a feature that will allow a user to add a new item to this datagrid. I will have an Add button in the app that when clicked, will open a new window where all the info will be added. After the user inputs the info into the text boxes and clicks save, that info gets saved to the database. This will require inserting data into two separate tables that are related. The first table is ItemDescriptor and the other table is Accessories. The id for ItemDescriptor has to be put into the Accessories table as ItemDescriptorID. I have tried to do two separate insert queries but cant figure out how to get the id from ItemDescriptor into the Accessories table programatically. Sorry, I know this might be a little confusing. Let me know if more info is needed. Thanks
_dbAccess.ExecuteNonQuery("INSERT INTO ItemDescriptor (id, Model, Brand, DeviceName, Type, Notes) VALUES ('" + System.Guid.NewGuid() + "', '" + tbModel.Text + "', '" + tbBrand.Text + "', '" + tbDeviceName.Text + '", '" + cmbType.SelectedValue + "', '" + tbNotes.Text + "')");
_dbAccess.ExecuteNonQuery("INSERT INTO Accessories (id, ItemDescriptorID, StorageRoomCount, OnHandCount, HiBayCount) VALUES ('" + System.Guid.NewGuid() + "', '" +
and thats about as far as i got...not sure how to get the ItemDescriptorID in there from the first query.
First, please please please use parameterized queries when dealing with user-supplied input. That string concatenation stuff is just asking for a SQL injection attack.
Second of all, if you're using SQL Server, you can use something like ##IDENTITY to get the identity field after insertion. There's something comparable on all systems, so if you let us know what you're using we can point you in the right direction.
I'm assuming that you're using SQL Server and that ItemDescriptor.id is an identity column; correct?
If you execute the following command immediately after your initial insert statement, it will return the value of the most recently generated identity:
var newID = _dbAccess.ExecuteScalar("SELECT Scope_Identity()");
You can use newID to construct your second insert statement.
One caveat: The SELECT Scope_Identity() statement must be executed on the same connection instance as the initial insert statement. So ensure that you're not closing and reopening your connection between statements. If this seems to be a problem, you can actually combine your insert and select statements into a single command; e.g.:
var newID = _dbAccess.ExecuteScalar("INSERT [all your code here]; SELECT Scope_Identity();");
Good luck!
Check out this site about Getting the identity of the most recently added record
I figured out a way to make it work. I just made the guid an object and then used it as a variable and that worked. thanks for all the suggestions.
Guid guid = System.Guid.NewGuid();
if (_dbaccess != null)
{
_dbAccess.ExecuteNonQuery("INSERT INTO ItemDescriptor (id, Model, Brand, DeviceName, Type, Notes) VALUES ('" + guid + "', '" + tbModel.Text + "', '" + tbBrand.Text + "', '" + tbDeviceName.Text + '", '" + cmbType.SelectedValue + "', '" + tbNotes.Text + "')");
_dbAccess.ExecuteNonQuery("INSERT INTO Accessories (id, ItemDescriptorID, StorageRoomCount, OnHandCount, HiBayCount) VALUES ('" + System.Guid.NewGuid() + "', '" + guid + "', '" + tbStorageRoom.Text + "', '" + tbOnHand.Text + "', '" + tbHiBay.Text + "')");
}

Categories

Resources