Foreign Key Error When adding new records - c#

I am making a gym management system and I am using foreign keys in my tables. Everything was working perfectly, but after I added foreign keys I am getting the following error:
SQLException was Unhandled
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_member_info_instructor_info". The conflict occurred in database "D:\GYM MANAGEMENT
SYSTEM\GYM MANAGEMENT SYSTEM\BIN\DEBUG\GMSDATABASE.MDF", table "dbo.instructor_info",
column 'InstructorID'.
The statement has been terminated.
This error is pointing to this code:
public void UpdateDatabase(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new
System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
The above code is in my database collection class which is as following:
class GMSDConnectionClass
{
System.Data.SqlClient.SqlDataAdapter da_1;
System.Data.SqlClient.SqlConnection con;
public string sql_string;
public string strCon;
public string Sql
{
set { sql_string = value; }
}
public string connection_string
{
set { strCon = value; }
}
public System.Data.DataSet GetConnection
{
get { return MyDataSet(); }
}
public System.Data.DataSet MyDataSet()
{
con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_data_1");
con.Close();
return dat_set;
}
public void UpdateDatabase(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new
System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
These are my tables which are being used when the error is thrown:
instructor_info table:
CREATE TABLE [dbo].[instructor_info] (
[InstructorID] INT IDENTITY (1, 1) NOT NULL,
[instructor] NVARCHAR (50) NOT NULL,
[father_name] NVARCHAR (50) NULL,
[age] NCHAR (10) NULL,
[address] NVARCHAR (MAX) NULL,
[contact] NVARCHAR (50) NULL,
[height] NCHAR (10) NULL,
[weight] NCHAR (10) NULL,
[chest] NCHAR (10) NULL,
[triceps_biceps] NCHAR (10) NULL,
[waist] NCHAR (10) NULL,
[shoulders] NCHAR (10) NULL,
[thighs] NCHAR (10) NULL,
[calves] NCHAR (10) NULL,
[memberID] INT NULL,
[date_of_admission] DATE NULL,
[photo] IMAGE NULL,
PRIMARY KEY CLUSTERED ([InstructorID] ASC),
CONSTRAINT [FK_instructor_info_member_info] FOREIGN KEY ([memberID]) REFERENCES [dbo].
[member_info] ([memberID])
);
member_info table:
CREATE TABLE [dbo].[member_info] (
[memberID] INT IDENTITY (1, 1) NOT NULL,
[memberName] NVARCHAR (50) NULL,
[father_name] NVARCHAR (50) NULL,
[age] NCHAR (10) NULL,
[address] NVARCHAR (50) NULL,
[contact] NVARCHAR (50) NULL,
[height] NVARCHAR (50) NULL,
[weight] NVARCHAR (50) NULL,
[chest] NVARCHAR (50) NULL,
[triceps_biceps] NVARCHAR (50) NULL,
[waist] NVARCHAR (50) NULL,
[shoulders] NVARCHAR (50) NULL,
[thighs] NVARCHAR (50) NULL,
[calves] NVARCHAR (50) NULL,
[instructorID] INT NULL,
[date_of_admission] DATE NULL,
[photo] IMAGE NULL,
PRIMARY KEY CLUSTERED ([memberID] ASC),
CONSTRAINT [FK_member_info_instructor_info] FOREIGN KEY ([instructorID]) REFERENCES
[dbo].[instructor_info] ([InstructorID])
);
This is my code for the save button on my form:
private void saveBtn_Click(object sender, EventArgs e)
{
DataRow row = memberDataS.Tables[0].NewRow();
row[0] = maxRowsMember + 1;
row[1] = memberName.Text;
row[2] = fatherName.Text;
row[3] = age.Text;
row[4] = address.Text;
row[5] = contact.Text;
row[6] = height.Text;
row[7] = weight.Text;
row[8] = chest.Text;
row[9] = tricepBicep.Text;
row[10] = waist.Text;
row[11] = shoulders.Text;
row[12] = thighs.Text;
row[13] = calves.Text;
row[14] = int.Parse(instructor.Text);
row[15] = dateTimePicker1.Text;
memberDataS.Tables[0].Rows.Add(row);
memberString.UpdateDatabase(memberDataS);
maxRowsMember += 1;
inc = maxRowsMember - 1;
MessageBox.Show("Database updated");
cancelBtn.Enabled = false;
saveBtn.Enabled = false;
addNewMemberBtn.Enabled = true;
}
All help will be appreciated. Thanks a lot.

I believe that your error may be resulting from row 14:
row[14] = int.Parse(instructor.Text);
If my assumption about your code is correct, the instructor variable contains the VARCHAR(50) instructor name, not the INT IDENTITY value of instructorID.

Related

SSIS C# SQLBulkCopy .csv file Error: Failed to convert parameter value from a String to a Boolean. String not recognized as a valid Boolean

I am trying to create a generic module that will load .csv files into SQL tables. The SQL tables are already created and their names, and the name of the file, will be passed as parameters. This what I have so far...
public void Main()
{
var mFilepath = Dts.Variables["InputFile"].Value.ToString();
var mSQLTable = "[Staging].[tblLoadBUF]";
Dts.Variables["StagingTableGetColumnsScript"].Value =
"IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tblLoadBUF') " +
"BEGIN; " +
"SELECT COLUMN_NAME " +
"FROM INFORMATION_SCHEMA.COLUMNS " +
"WHERE TABLE_NAME = 'tblLoadBUF'; " +
"END; ";
string connectionString = Dts.Connections["OLEDB_CONN"].ConnectionString;
connectionString = connectionString.Trim(';');
var connStrDictionary = connectionString.Split(';').Select(x => x.Split('=')).ToDictionary(x => x[0], x => x[1]);
connectionString = "Data Source=" + connStrDictionary["Data Source"] + ";Initial Catalog=" + connStrDictionary["Initial Catalog"] + ";Integrated Security=" + connStrDictionary["Integrated Security"];
try
{
DataTable dt = new DataTable();
string contents = File.ReadAllText(mFilepath, System.Text.Encoding.GetEncoding(1252));
TextFieldParser parser = new TextFieldParser(new StringReader(contents));
parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");
string[] fields;
while (!parser.EndOfData)
{
fields = parser.ReadFields();
if (dt.Columns.Count == 0)
{
foreach (string field in fields)
{
dt.Columns.Add(new DataColumn(string.IsNullOrWhiteSpace(field.Trim('\"')) ? null : field.Trim('\"'), typeof(string)));
}
}
else
{
dt.Rows.Add(fields.Select(item => string.IsNullOrWhiteSpace(item.Trim('\"')) ? null : item.Trim('\"')).ToArray());
}
}
parser.Close();
var columnNames = new List<string>();
using (var cn = new SqlConnection() { ConnectionString = connectionString })
{
using (var cmd = new SqlCommand() { Connection = cn })
{
cmd.CommandText = Dts.Variables["StagingTableGetColumnsScript"].Value.ToString();
cn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
columnNames.Add(reader.GetString(0));
}
cn.Close();
}
}
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
sqlBulkCopy.DestinationTableName = mSQLTable;
sqlBulkCopy.ColumnMappings.Clear();
con.Open();
foreach (var column in columnNames)
{
sqlBulkCopy.ColumnMappings.Add(column.ToString(), column.ToString());
}
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception ex)
{
Dts.Events.FireError(0, "Something went wrong ", ex.ToString(), string.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
I get the following error message at execution:
System.InvalidOperationException: The given value of type String from the data source cannot be converted to type bit of the specified target column. ---> System.FormatException: Failed to convert parameter value from a String to a Boolean. ---> System.FormatException: String was not recognized as a valid Boolean.
Can somebody help me fix this ? I understand the error message, but I find it strange that it doesn't complain about decimal or integer values.
Here is my SQL Table:
CREATE TABLE [Staging].[tblLoadBUF](
[Bg_SN] [NVARCHAR](12) NOT NULL,
[Bg_Type] [NVARCHAR](7) NOT NULL,
[Bg_Expected_BUs] [NUMERIC](4, 0) NOT NULL,
[Bg_Validity_Likelihood] [DECIMAL](5, 4) NOT NULL,
[Bg_Mixed_Usage] [NUMERIC](1, 0) NOT NULL,
[Bg_Status] [NVARCHAR](1) NOT NULL,
[BU_SN] [NVARCHAR](12) NOT NULL,
[BU_Residential_Occup_Likelihood] [DECIMAL](5, 4) NOT NULL,
[BU_Last_Res_Confirmation] [DATE] NULL,
[BU_Last_NRes_Usage] [NVARCHAR](7) NULL,
[BU_Last_NRes_Confirmation] [DATE] NULL,
[BU_Validity_Likelihood] [DECIMAL](5, 4) NOT NULL,
[BU_Status] [NVARCHAR](1) NOT NULL,
[BU_Mailing_Address_Availability] [NUMERIC](1, 0) NOT NULL,
[BU_Mailing_Address_Likelihood] [DECIMAL](5, 4) NULL,
[BU_Usage] [NUMERIC](1, 0) NOT NULL,
[BU_Co_SN] [NVARCHAR](12) NULL,
[Co_Type] [NVARCHAR](5) NULL,
[Co_Validity_Likelihood] [DECIMAL](5, 4) NULL,
[Co_Status] [NVARCHAR](1) NULL,
[TN_LTotal] [INT] NOT NULL,
[TN_CTotal] [INT] NOT NULL,
[TN_OTotal] [INT] NOT NULL,
[TN_Total] [INT] NOT NULL,
[EA_Total] [INT] NOT NULL,
[BB_UID] [NUMERIC](10, 0) NULL,
[BB_BPIR] [NVARCHAR](4) NOT NULL,
[CUID] [NVARCHAR](8) NULL,
[COLB] [NVARCHAR](10) NULL,
[DAID] [NVARCHAR](8) NULL,
[DISB] [NVARCHAR](11) NULL,
[CSD_Name] [NVARCHAR](100) NULL,
[CSD_UID] [NVARCHAR](7) NULL,
[CSD_Type] [NVARCHAR](3) NULL,
[SAC_Code] [NVARCHAR](3) NULL,
[PC_CUID] [NVARCHAR](8) NULL,
[PC_DAID] [NVARCHAR](8) NULL,
[PC_CSD_UID] [NVARCHAR](7) NULL,
[PC_CSD_Type] [NVARCHAR](3) NULL,
[PC_SAC_Code] [NVARCHAR](3) NULL,
[LFS_UID] [NVARCHAR](13) NULL,
[ER_UID] [NVARCHAR](4) NULL,
[HR_UID] [NVARCHAR](4) NULL,
[PRCODE] [NVARCHAR](2) NOT NULL,
[BU_CPC_Postal_Code] [NVARCHAR](6) NULL,
[Bg_Latitude] [DECIMAL](9, 6) NULL,
[Bg_Longitude] [DECIMAL](11, 6) NULL,
[Bg_Coordinate_Type] [NVARCHAR](1) NOT NULL,
[AR_UID] [NVARCHAR](10) NULL,
[Frame_ID] [NVARCHAR](8) NULL,
[Do_Not_Contact_Flag] [BIT] NULL,
PRIMARY KEY CLUSTERED
(
[BU_SN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
And my .csv file contains values of 1 and 0 in column [Do_Not_Contact_Flag].
Pease note that English is not my primary language, so just let me know if this is not clear enough. And thanks in advance for you help :-)
Mylene
I found the solution !!
I've modified my staging table column [Do_Not_Contact_Flag] to be SMALLINT, and added the conversion to BIT in my processing stored proc before loading in the final SQL Table.

SQL/C#: DataTable to stored procedure (INSERT from user-defined table type) - Converting error

I am trying to pass my DataTable to a stored procedure. The DataTable holds the contents of an Excel sheet. The Excel sheet has two empty columns, five with text, and five with decimal numbers.
The empty columns are OppdragsMVAkode and OppdragsgebyrMVAkode.
If I run my application, I get this exception:
System.ArgumentException: Input string was not in a correct format. Couldn't store <> in OppdragsMVAkode Column. Expected type is Decimal.
If I add a temporary number, I get this exception:
System.Data.SqlClient.SqlException: Error converting data type nvarchar to numeric.
I don't get why it's reading it as a string.
My stored procedure (spGetTrips):
ALTER PROCEDURE [dbo].[spGetTrips]
#trips udtTripsPerMonth readonly
AS
BEGIN
INSERT INTO tblTripsPerMonth
SELECT
[KjøretøyID],
SUBSTRING([År], 7, 4),
SUBSTRING([Måned], 4, 2),
[Betaling (brutto)],
[Betaling (netto)],
[Bestillingsgebyr (netto)],
[Betalingsgebyr (netto)],
[OppdragsMVAkode],
CONCAT(LøyvehaverFakturaID, + 'UF-' + SUBSTRING([År], 9, 2) + SUBSTRING([Måned], 4, 2)),
[Oppdragsgebyr (netto)],
[OppdragsgebyrMVAkode],
CONCAT([RidelRegionFakturaID], + 'UF-' + SUBSTRING([År], 9, 2) + SUBSTRING([Måned], 4, 2))
FROM #trips
UPDATE tblTripsPerMonth
SET [OppdragsMVAkode] = (
SELECT [ID]
FROM [tblMVAkoder]
WHERE [ID] = 'MVAkode2'
);
UPDATE tblTripsPerMonth
SET [OppdragsgebyrMVAkode] = (
SELECT [ID]
FROM [tblMVAkoder]
WHERE [ID] = 'MVAkode5'
);
END
As you can see above, I am setting the value of the two empty columns with UPDATE clauses in the Stored Procedure. Whether they are empty in the Excel sheet, or with some preliminary value, and then to be overridden, I care not - I just want it to work.
Here's my User-Defined Table Type (udtTripsPerMonth):
CREATE TYPE [dbo].[udtTripsPerMonth] AS TABLE(
[KjøretøyID] [nvarchar](50) NULL,
[År] [nvarchar](50) NULL,
[Måned] [nvarchar](50) NULL,
[Betaling (brutto)] [decimal](10, 2) NULL,
[Betaling (netto)] [decimal](10, 2) NULL,
[Bestillingsgebyr (netto)] [decimal](10, 2) NULL,
[Betalingsgebyr (netto)] [decimal](10, 2) NULL,
[OppdragsMVAkode] [decimal](10, 2) NULL,
[LøyvehaverFakturaID] [nvarchar](50) NULL,
[Oppdragsgebyr (netto)] [decimal](10, 2) NULL,
[OppdragsgebyrMVAkode] [decimal](10, 2) NULL,
[RidelRegionFakturaID] [nvarchar](50) NULL
)
GO
And my table (tblTripsPerMonth):
CREATE TABLE [dbo].[tblTripsPerMonth](
[ID] [int] IDENTITY(1,1) NOT NULL,
[KjøretøyID] [nvarchar](50) NULL,
[År] [nvarchar](50) NULL,
[Måned] [nvarchar](50) NULL,
[Betaling (brutto)] [decimal](10, 2) NULL,
[Betaling (netto)] [decimal](10, 2) NULL,
[Bestillingsgebyr (netto)] [decimal](10, 2) NULL,
[Betalingsgebyr (netto)] [decimal](10, 2) NULL,
[OppdragsMVAkode] [decimal](10, 2) NULL,
[LøyvehaverFakturaID] [nvarchar](50) NULL,
[Oppdragsgebyr (netto)] [decimal](10, 2) NULL,
[OppdragsgebyrMVAkode] [decimal](10, 2) NULL,
[RidelRegionFakturaID] [nvarchar](50) NULL,
PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
The other table I reference in the UPDATE clauses (tblMVAkoder):
CREATE TABLE [dbo].[tblMVAkoder](
[ID] [nvarchar](50) NOT NULL,
[Startdato] [date] NULL,
[Sluttdato] [date] NULL,
[MVAsats] [decimal](10, 2) NULL,
PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
Here's my C# code (Excel to DataTable):
private void btnExport_Click(object sender, RoutedEventArgs e) {
OpenFileDialog of = new();
of.Filter = "Excel Files | *.xlsx;";
of.Title = "Importer Excel fil.";
if (of.ShowDialog() == true) {
dgPaidTrip.ItemsSource = ImportExceltoDataTable(of.FileName).DefaultView;
btnClearForm.IsEnabled = true;
}
using (SqlConnection con = new(ConnectionString.connectionString))
using (var cmd = new SqlCommand("spGetTrips", con) { CommandType = CommandType.StoredProcedure }) {
con.Open();
DataTable dt = ImportExceltoDataTable(of.FileName);
cmd.Parameters.Add(new SqlParameter("#trips", dt));
cmd.ExecuteNonQuery();
}
}
public static DataTable ImportExceltoDataTable(string filePath) {
using (XLWorkbook wb = new(filePath)) {
IXLWorksheet ws = wb.Worksheet(1);
int tl_Row = ws.FirstCellUsed().Address.RowNumber;
int tl_Col = ws.FirstCellUsed().Address.ColumnNumber;
int br_Row = ws.LastCellUsed().Address.RowNumber;
int br_Col = ws.LastCellUsed().Address.ColumnNumber;
DataTable dt = new();
dt.Columns.Add("KjøretøyID", typeof(string));
dt.Columns.Add("År", typeof(string));
dt.Columns.Add("Måned", typeof(string));
dt.Columns.Add("Betaling (brutto)", typeof(decimal));
dt.Columns.Add("Betaling (netto)", typeof(decimal));
dt.Columns.Add("Bestillingsgebyr (netto)", typeof(decimal));
dt.Columns.Add("Betalingsgebyr (netto)", typeof(decimal));
dt.Columns.Add("OppdragsMVAkode", typeof(decimal));
dt.Columns.Add("LøyvehaverFakturaID", typeof(string));
dt.Columns.Add("Oppdragsgebyr (netto)", typeof(decimal));
dt.Columns.Add("OppdragsgebyrMVAkode", typeof(decimal));
dt.Columns.Add("RidelRegionFakturaID", typeof(string));
IXLRow currentRow;
for (int dtRow = 0; dtRow < br_Row - tl_Row; dtRow++) {
currentRow = ws.Row(tl_Row + dtRow + 1);
dt.Rows.Add();
for (int dtCol = 0; dtCol < br_Col - tl_Col + 1; dtCol++) {
dt.Rows[dtRow][dtCol] = currentRow.Cell(tl_Col + dtCol).Value;
}
}
return dt;
}
}
As far as I can see, all my column types match, as well as their order.
I changed all my types to nvarchar, and the code "works".
But someone smarter than me told me it was not a good idea to fake the column types.
What am I missing?
To pass a null value, you need to set the column value as DBNull.Value. You can set DBNull like this
dt.Rows[dtRow][dtCol] = currentRow.Cell(tl_Col + dtCol).Value ?? (object)DBNull.Value;
You must also set SqlDBType TypeName and Direction properties
cmd.Parameters.Add(
new SqlParameter("#trips", SqlDBType.Structured)
{
TypeName = "dbo.udtTripsPerMonth",
Direction = ParameterDirection.Input,
Value = dt
});

Select data from two tables with Linq/Lambda

When the customer logs in with Social Security Number to the website I want it to show the customers Accountname, Accountnumber and Balance. These information have to be fetched through database.
Accounts table:
CREATE TABLE [dbo].[Accounts] (
[id] BIGINT IDENTITY (1, 1) NOT NULL,
[accountnumber] VARCHAR (50) NULL,
[accountname] VARCHAR (50) NULL,
[SSN] BIGINT NOT NULL,
[CustomerId] INT NULL,
[balance] VARCHAR (50) NULL,
[BalanceId] INT NULL,
[AccountId] INT NULL,
CONSTRAINT [PK_dbo.Accounts] PRIMARY KEY CLUSTERED ([id] ASC),
CONSTRAINT [FK_dbo.Accounts_dbo.Customer] FOREIGN KEY ([SSN]) REFERENCES [dbo].[Customer] ([SSN])
);
GO
CREATE NONCLUSTERED INDEX [IX_SSN]
ON [dbo].[Accounts]([SSN] ASC);
Customer table:
CREATE TABLE [dbo].[Customer] (
[id] BIGINT IDENTITY (1, 1) NOT NULL,
[Firstname] VARCHAR (50) NULL,
[Lastname] VARCHAR (50) NULL,
[SSN] BIGINT NOT NULL,
[Password] VARBINARY (MAX) NULL,
[ConfirmPassword] VARCHAR (MAX) NULL,
[Salt] VARCHAR (MAX) NULL,
[AccountId] INT NULL,
[BalanceId] INT NULL,
[RegPayId] INT NULL,
[ConfirmedRegPayId] INT NULL,
[CustomerId] INT NULL,
CONSTRAINT [PK_dbo.Customer] PRIMARY KEY CLUSTERED ([SSN] ASC)
);
But this code shows me no customer:
List<AccountsCTX> everyBalance = db.Accounts.Join(db.Customer, a => a.id,
c => c.SSN,
(a, c) => new AccountsCTX()
{
//id = a.id,
SSN = a.SSN,
accountname = a.accountname,
accountnumber = a.accountnumber,
balance = a.balance
}
).ToList();
return everyBalance;
I have "id" as the primary key from table "Accounts" and "SSN" as the foreign key from table "Customer".
I'm still freshman in programming so need more practice xD
Let me know for more details and appreciate all the help I can get!
actually i dont see any relation between the two tables provided except SSN, this inner join will fetch you all the records which has same SSN id in both the tables:
List<AccountsCTX> everyBalance = db.Accounts.Join(db.Customer, a => a.SSN,
c => c.SSN,
(a, c) => new AccountsCTX()
{
SSN = a.SSN,
accountname = a.accountname,
accountnumber = a.accountnumber,
balance = a.balance
}).Where(x=>x.SSN==InputSSN).ToList();
return everyBalance;
You can try
public static AccountsCTX GetEveryBalance(long currentCustomerSsn)
{
AccountsCTX everyBalance = db.Accounts.Join(db.Customer, a => a.SSN,
c => c.SSN,
(a, c) => new AccountsCTX()
{
//id = a.id,
SSN = a.SSN,
accountname = a.accountname,
accountnumber = a.accountnumber,
balance = a.balance
}
).Where(x=>x.SSN==currentCustomerSsn).FirstOrDefault();//currentCustomerSsn is enter ssn by Customer
return everyBalance;
}
//Create customer
public long insertCusReg(CustomerCTX inCusReg)
{
...
try
{
...
return inCusReg.SSN;
}
catch (Exception)
{
return 0;
}
}
Call Method
currentCustomerSsn=insertCusReg(CustomerCTX);// pass CustomerCTX object
AccountsCTX everyBalance=GetEveryBalance(currentCustomerSsn);

Gridview in C# dont show data and a big error

I am trying to display my data table with a grid view
protected void show_data(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;";
str += "AttachDbFilename=|DataDirectory|DinoData.mdf;";
str += "Integrated Security= True";
SqlConnection c;
c = new SqlConnection(str);
GV.DataSource = User;
GV.DataBind();
}
the error:
An exception of type 'System.InvalidOperationException' occurred in
System.Web.dll but was not handled in user code
Additional information: Data source is an invalid type. It must be
either an IListSource, IEnumerable, or IDataSource.
user table:
CREATE TABLE [dbo].[User] (
[Username] VARCHAR (100) NOT NULL,
[Pasword] VARCHAR (100) NOT NULL,
[FName] VARCHAR (MAX) NOT NULL,
[LName] VARCHAR (MAX) NOT NULL,
[Location] VARCHAR (MAX) NOT NULL,
[Profesion] VARCHAR (MAX) NOT NULL,
[email] VARCHAR (MAX) NOT NULL,
[gender] VARCHAR (MAX) NOT NULL,
[money] INT NOT NULL,
[property] VARCHAR (MAX) NULL,
[xp] INT NOT NULL,
[level] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Username] ASC)
);
What should i do?
If I want to show only part of the table with gridview how to do it?
You have no query to select rows from your database ,you must have a selection statment like :
protected void show_data(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;";
str += "AttachDbFilename=|DataDirectory|DinoData.mdf;";
str += "Integrated Security= True";
SqlConnection c;
c = new SqlConnection(str);
DataTable dt = new DataTable();
//For exemple t select all rows in you Table User,you can insert a condition here
String req = "SELECT * FROM [User]";
SqlDataAdapter da = new SqlDataAdapter(req, c);
da.Fill(dt);
GV.DataSource = dt;
GV.DataBind();
}

Show Projects Assigned to a User Who Logins From Projects Assigned To Many Users

I have two tables tbl_Staff which contains the User details and tbl_ProjectInformation which contains the project details which are assigned to different users.
What I need to do is , When a user logins I want to show only the list of projects of tbl_ProjectInformation which are assigned to the user who logins in form FrmUserRole on datagridview
dgvGetUserProject.
LoginForm Code:
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
DataTable result = uc.Login(txtUserName.Text, txtPassword.Text);
if (result.Rows.Count == 1)
{
this.Hide();
string role = result.Rows[0]["Roles"].ToString();
switch (role)
{
case "Admin":
UserPanelFrm frm = new UserPanelFrm();
frm.ShowDialog();
this.Close();
break;
case "User":
FrmUserRole fur = new FrmUserRole();
fur.ShowDialog();
this.Close();
break;
}
}
else
{
MessageBox.Show("INVALID USERNAME OR PASSWORD");
txtPassword.Clear();
txtPassword.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
tbl_Staff
CREATE TABLE [dbo].[tbl_Staff](
[StaffID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[Address] [nvarchar](500) NULL,
[Phone] [nvarchar](100) NULL,
[Email] [nvarchar](100) NULL,
[JoinedDate] [date] NULL,
[Username] [nvarchar](50) NULL,
[Password] [nvarchar](max) NULL,
[CreatedDate] [date] NULL,
[Roles] [nvarchar](200)
)
tbl_ProjectInformation
CREATE TABLE [dbo].[tbl_ProjectInformation](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ProjectID] [int] NOT NULL,
[BusinessName] [nvarchar](100) NOT NULL,
[ContactPerson] [nvarchar](100) NOT NULL,
[Phone] [nvarchar](200) NULL,
[Address] [nvarchar](100) NOT NULL,
[CreatedDate] [date] NULL,
[AssignedTo] [nvarchar](100) NULL,
[Status] [nvarchar](100) NULL,
[CompletedDate] [date] Null
)
What I have done is bind the datagrid view to a table but coundn't understand to pass the login user id to sql script. Following are the script I used to get project list of only one user. I need to pass login user StaffId to sql script and show project assigned to that StaffId User.
ProjcetClass.css
public DataTable SelectUserProjects()
{
try
{
SqlCommand cmd = new SqlCommand("select tbl_ProjectInformation.ProjectID,tbl_ProjectInformation.BusinessName,tbl_ProjectInformation.ContactPerson,tbl_ProjectInformation.Phone,tbl_ProjectInformation.Address,tbl_ProjectInformation.CreatedDate,tbl_ProjectInformation.Status,tbl_ProjectInformation.CompletedDate from tbl_ProjectInformation,tbl_Staff where tbl_Staff.StaffID='7'", conn);
DataTable dt = new DataTable();
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dt.Load(dr);
conn.Close();
return dt;
}
catch (Exception ex)
{
throw ex;
}
}
DataGrid View Binding in FrmUserRole
private void FrmUserRole_Load(object sender, EventArgs e)
{
dgvGetUserProject.DataSource = pc.SelectUserProjects();
}

Categories