C# and SQL System.ArgumentOutOfRangeException - c#

I am attempting to create an application which connects to a database using sql and I am trying to create a dataview which looks at the current selected dataview and then pulls back information from another table. I have followed some guides and have gotten fairly close but I am currently getting this error:
An unhandled exception of type 'System.ArgumentOutOfRangeException'
occurred in mscorlib.dll Additional information: Index was out of
range. Must be non-negative and less than the size of the collection.
Any help would greatly be appreciated. (Visual Studio shows the error at the end of the first line below)
string PersonID = Grid1.SelectedRows[0].Cells[0].Value.ToString();
sqlDataAdapter2.SelectCommand.CommandText = "select * from Personal_Emails where PersonID=" + PersonID;
sqlDataAdapter2.Fill(dataSet21.Personal_Emails);

You need to check if something exists before you can use it.
var selectedRow = Grid1.SelectedRows[0];
var cell = selectedRow == null ? false : selectedRow.Cells.Any();
var personID = (cell) ? Grid1.SelectedRows[0].Cells[0].Value.ToString() : "";
if(!string.isNullOrEmpty(personID)
// do query stuff

string PersonID = Grid1.SelectedRows[0].Cells[0].Value.ToString();
verify if this line is returning some value <> null.
example : if the grid has no selected rows it will return error or empty value.

Have you checked that SelectedRows & Cells have a selected value? You could use the debugger and see what the values are.
Also:
You are defining PersonID as a string. Is it a string value in your database? If so, have you tried:
sqlDataAdapter2.SelectCommand.CommandText = "SELECT * FROM Personal_Emails WHERE PersonID='" + PersonID + "'";

Related

OutOfRange exception when selecting data from SQL table in DATAGRIDVIEW

I am trying to create a Winforms app where I store info in a database and view them (datagridview) using SQL. I am attempting to make it so that I can pull out data from a selected row and be able to modify it later but I am getting an error. I can view the data from SQL just fine in the table but when trying to get selected row data from SQL table to display in textboxes the following exception appears :
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Arg_ParamName_Name'
C# code :
private void MemberSDGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
NomTb.Text = MemberSDGV.SelectedRows[0].Cells[3].Value.ToString();
PrenomTb.Text = MemberSDGV.SelectedRows[0].Cells[4].Value.ToString();
AgeTb.Text = MemberSDGV.SelectedRows[0].Cells[6].Value.ToString();
AddressTb.Text = MemberSDGV.SelectedRows[0].Cells[13].Value.ToString();
EmailTb.Text = MemberSDGV.SelectedRows[0].Cells[14].Value.ToString();
gsmpTb.Text = MemberSDGV.SelectedRows[0].Cells[9].Value.ToString();
gsmmTb.Text = MemberSDGV.SelectedRows[0].Cells[12].Value.ToString();
gsmTb.Text = MemberSDGV.SelectedRows[0].Cells[5].Value.ToString();
}
Is there something I'm doing wrong here?
Apparently there is no selected row.
Use the RowIndex from DataGridViewCellEventArgs instead.
NomTb.Text = MemberSDGV.Rows[e.RowIndex].Cells[3].Value.ToString();
https://learn.microsoft.com/.../selected-cells-rows-and-columns-datagridview
column headers in DGV are also cells, so clicking on the header "row" results in RowIndex being -1. Include the following code to avoid exceptions:
if (e.RowIndex < 0)
{
return;
}

Getting "0" (invalid data ) from Sqlite command

I am trying to fetch a column a from table, but it gets 0 value and column contains a value which is (2).
here is my code
obj.GetCon().Open();
obj.cmd = new SQLiteCommand("SELECT Payable FROM VendorLedgers WHERE VendorId=" + Convert.ToInt32( payBill.VendorId), obj.con);
obj.read = obj.cmd.ExecuteReader();
while (obj.read.Read())
{
MessageBox.Show(obj.read.GetValue(0).ToString());
dues = obj.read["Payable"].ToString();
string[] split_due = dues.Split('(', ')');
int dueamount1 = Convert.ToInt32(split_due[1]); //and it prints here index was outside the bound error
dueamount.Add(dueamount1);
}
obj.GetCon().Close();
and here is my query output on database
please help if anyone know how to fix it
I have not worked for SQLite. But with while(obj.read.Read()) you read one row at a time.
Then access the corresponding column with obj.read["Payable"].
So what do you need split!
while (obj.read.Read())
{
MessageBox.Show(obj.read.GetInt32(0).ToString());
int dueamount1 = obj.read.GetInt32(0);
dueamount.Add(dueamount1);
}

Store Sql Function Value in string

I have function in SQL as above, i want the value 'INTERNATIONAL' stored in the string('strIntlStudent'). How can i accomplish that? I know data reader but column has no name.
string TSQL_INTERNATIONAL = "select TOP 1 campus6.dbo.fndqgetpopulation_of_YT_v2a ('P000170620', '2017', '03TERM')";
DataTable DT_INTERNATIONAL = dhelper.ExecuteSelectCommand(TSQL_INTERNATIONAL, CommandType.Text);
if (DT_INTERNATIONAL != null && DT_INTERNATIONAL.Rows.Count > 0)
{
strIntlStudent = DT_INTERNATIONAL.Rows[0]["it says no column name"].ToString();
}
You need to give your column a name. Try this:
select TOP 1 campus6.dbo.fndqgetpopulation_of_YT_v2a
('P000170620', '2017', '03TERM') AS some_name
Then you can use that name:
strIntlStudent = DT_INTERNATIONAL.Rows[0]["some_name"].ToString();
Alternatively, if you are only retrieving one value, then you can use ExecuteScalar function which returns one value regardless of the column name and you don't need to bother with a table. Check your dhelper class to see if it has a function related to ExecuteScalar.

object must implement IConvertible error in linq query to select two rows

I have an Excel sheet , I need to fetch two columns values - I have written a Linq query -
Error:
contextSwitchDeadLock was detected error at line
Query:
select new { Description = typeDescription.Description ,
VehicleKey = typeDescription.VehicleKey });
how can i fix this error - i want to fetch two coulmns value from the same Excel sheet , from a single linq Query.
I think its due to null values
try like this.
select new { Description = Convert.ToString(typeDescription.Description) ,
VehicleKey = Convert.ToString(typeDescription.VehicleKey) });

Index out of range exception when using this query from C#

I am using a calculation in my SQL query. How can I use that calculated field in C#? When I try, I get an index out of range exception.
My query is:
Select OwnerCompanyLog.olog_name,inlt_companyid,inlt_childcompid,inlt_effectinterest,inlt_percent,inlt_sharetype,inlt_shares,inlt_childbase,inlt_effdate,
((inlt_percent * inlt_effectinterest)/100)eff
from InterestLogTable
INNER JOIN OwnerCompanyLog
ON
InterestLogTable.inlt_childcompid = OwnerCompanyLog.olog_companyid
where inlt_companyid=5
Order By inlt_childcompid
I want to use inlt_percent * inlt_effectinterest)/100 in my C# code:
entity.ParentCompany = new List<Company>();
while (parentCompanyReader.Read())
{
ParentCompany.Effect = parentCompanyReader["eff"].ToString();
entity.ParentCompany.Add(ParentCompany);
}
parentCompanyReader.Close();
But I got the error above.
the problem is only with calculated field. The above comment is absolutely correct. It could be your parentCompanyReader class that has the error. Meanwhile could you try few things to confirm the error.
Move the eff column to some middle. It could be that your parentCompanyReader would not be able to deal with only a limited number of column.
Also what is "eff" here, a column ? Also put a AS after the calculated column.
Select (inlt_percent * inlt_effectinterest)/100)eff AS EFF, OwnerCompanyLog.olog_name,inlt_companyid,inlt_childcompid,inlt_effectinterest,inlt_percent,inlt_sharetype,inlt_shares,inlt_childbase,inlt_effdate
Note : these are just arrows in dark !
Try to use it with index rather than column name .
while (parentCompanyReader.Read())
{
ParentCompany.Effect = Convert.ToInt32(parentCompanyReader[5]);
entity.ParentCompany.Add(ParentCompany);
}
parentCompanyReader.Close();
Im assuming that the calculated field returns an integer
and also make sure u use using statement so that incase if there is an error then connection will be closed and disposed

Categories