show different column value from single column - c#

I want to show the single column value to gridview different column..
For example :
My column value is "Casual Leave:12-Medical Leave :13-Annual Leave :03" ..
I want to split the above string value and show the above values in a grid colulmn like this...
Employee Id Employee Name Casual Leave Medical Leave Annual Leave
00624323 James 12 13 03
00624324 Fernando 12 14 05
Note: Employee Id and Employee Name are different column
My partial code is here :
DataSet5TableAdapters.sp_getallempleaveTableAdapter TA = new DataSet5TableAdapters.sp_getallempleaveTableAdapter();
DataSet5.sp_getallempleaveDataTable DS = TA.GetData();
if (DS.Rows.Count > 0)
{
DataView datavw = new DataView();
datavw = DS.DefaultView;
datavw.RowFilter = "fldempid='" + txtempid.Text + "' and fldempname='" + txtempname.Text + "'";
if (datavw.Count > 0)
{
string leavehistory = Convert.ToString(datavw[0]["fldleavehistory"]);
string[] textarray = leavehistory.Split('-');
foreach (string samtext in textarray)
{
if (samtext.StartsWith(leavehistory))// I want to check the string with array value
{
string newtext = samtext.Split(':')[1];
}
}
}
}
what i do? please help me to solve this

Having such a compound column in your database is never a good idea. Why don't you just split the column into 3 columns (CasualLeave, MedicalLeave and AnnualLeave), each containing a number?

With the leavehistory and newtext either you can make a datatable and bind it to gridview or u can change your sp to directly return splitted result.
since u have coded so much in client side its now better to make a new datatable and feed rows into it and add this datatable to the gridsource
Edit :-
Example :-
DataTable newdatatable = new DataTable("New");
newdatatable.Columns.Add("Employee Id");
newdatatable.Columns.Add("Employee Name");
newdatatable.Columns.Add("Casual Leave");
newdatatable.Columns.Add("Medical Leave");
newdatatable.Columns.Add("Annual Leave");
newdatatable.AcceptChanges();
DataSet5TableAdapters.sp_getallempleaveTableAdapter TA = new DataSet5TableAdapters.sp_getallempleaveTableAdapter();
DataSet5.sp_getallempleaveDataTable DS = TA.GetData();
if (DS.Rows.Count > 0)
{
DataView datavw = new DataView();
datavw = DS.DefaultView;
datavw.RowFilter = "fldempid='" + txtempid.Text + "' and fldempname='" + txtempname.Text + "'";
if (datavw.Count > 0)
{
string leavehistory = Convert.ToString(datavw[0]["fldleavehistory"]);
string[] textarray = leavehistory.Split('-');DataRow drow = newdatatable.NewRow();
drow[0]=txtempid.Text;
drow[1]=txtempname.Text;
foreach (string samtext in textarray)
{
if (samtext.StartsWith(leavehistory))// I want to check the string with array value
{
drow[samtext.Split(':')[0]]=samtext.Split(':')[1];
}
}
newdatatable.Rows.Add(drow);
newdatatable.AcceptChanges();
}
}
gridview1.DataSource=newdatatable;

Related

How do I display a select from database consisting of multiple join in a text box?

I have to do a select from database that have multiple join( i will show you belong) and i put in one command . The problem it is next one : a select something from a table and when i run the code it tell me something like that : " Column '....' does not belong to table ." and i look into table and it is. I will put code for take a look. Do you have any idea? I am sure i do something wrong but i don t know what.
string connectionString = "Data Source=..." +
"User=..." +
"Password=..";
OracleConnection con = new OracleConnection();
con.ConnectionString = connectionString;
con.Open();
string select3 = "SELECT tblOwner.OwnerFirstName , tblOwner.OwnerLastName, tblOwner.OwnerEmailID, tblOwner.OwnerLoc, tblDomain.DomainName " +
" FROM tblDomain " +
" INNER JOIN(tblOwner INNER JOIN tblProductInfo ON tblOwner.OwnerID = tblProductInfo.OwnerID) ON tblDomain.DomainIDShort = tblOwner.DomainID" +
" WHERE(((tblProductInfo.Productname) = ' "+ mystring +
"'" + "))";
OracleDataAdapter aa = new OracleDataAdapter(select3, con);
DataTable cc = new DataTable();
bb.Fill(cc);
foreach (DataRow ww in dt.Rows)
{
textBox2.Text = (ww["DomainName"].ToString());
}
Your DataTable seems to not have a column called "DomainName". You can use the following code to list the existing column names in the output window of visual studio.
foreach (DataColumn col in cc.Columns)
{
Debug.WriteLine(col.ColumnName);
}
First: You are filling DataTable from different data adapter.
OracleDataAdapter aa = new OracleDataAdapter(select3, con); // aa created
DataTable cc = new DataTable();
bb.Fill(cc); // 'bb' fills data
Second: You are reading data from different DataTable, not that which you are filling with data.
DataTable cc = new DataTable();
bb.Fill(cc); // 'cc' variable filled with data
foreach (DataRow ww in dt.Rows) // reading rows from 'dt' variable
{
textBox2.Text = (ww["DomainName"].ToString());
}

How to combine two data fields in a database and display in a dropdownlist?

I have a query to get data in two columns and add another '-' sign to the result. Now i want to display these details in a dropdownlist. Also in another function I have to get the selected value's first part(first column of the table used to create the output) and store it in the database again. Query works perfectly.
Now my questions are,
1) How to display final result in of joined columns in the dropdownlist?
2)How to get the first column's value of the selected index of the dropdownlist?
Here is my code
public DataSet getSOCode()
{
string strQuery = #"select a.AGNTNUM+' - '+a.CLTADDR01
from AGNTDTL a, cscsuboffice b, Web_User_Group c
where
a.ARACDE=b.DESCITEM and
b.SHORTDESC=c.BRANCH and
a.DTETRM='99999999' and
a.AGNTNUM not between '00050000' and '00200000' and
a.agntnum <'00300000' and
a.agtype not in ('PA','LG','BK') and
c.EMPID='000101'
order by a.AGNTNUM";
return SqlHelper.ExecuteDataset(dwhConnString, CommandType.Text, strQuery);
}
This is the aspx.cs code
public void loadSOCode()
{
DataSet ds = new DataSet();
ds = db.getSOCode();
if (ds.Tables[0].Rows.Count > 0)
{
ddlSoCode.DataSource = ds.Tables[0];
ddlSoCode.DataTextField ="AGNTNUM" + "CLTADDR01";
ddlSoCode.DataValueField = "AGNTNUM" + "CLTADDR01";
ddlSoCode.DataBind();
ddlSoCode.Items.Insert(0, new ListItem("--Select The Agent--", "--Select The Agent--"));
}
}
Change the Query like the following:
string strQuery = #"select a.AGNTNUM , a.AGNTNUM + ' - ' + a.CLTADDR01 as DisplayItem " +
" from AGNTDTL a, cscsuboffice b, Web_User_Group c" +
" where .. // give conditions here
Then the code for binding will be :
ddlSoCode.DataSource = ds.Tables[0];
ddlSoCode.DataTextField ="DisplayItem";
ddlSoCode.DataValueField = "AGNTNUM";
ddlSoCode.DataBind();
So that the SelectedValue will give you the AGNTNUM and the combobox will display the combination of a.AGNTNUM and a.CLTADDR01
You cannot set DataTextField and DataValueField with the combination of column names, in fact sql returns no column name in this case. Use alias to give a new name.
public DataSet getSOCode()
{
string strQuery = #"select a.AGNTNUM+' - '+a.CLTADDR01 AS NewColumn
from AGNTDTL a, cscsuboffice b, Web_User_Group c
where
a.ARACDE=b.DESCITEM and
b.SHORTDESC=c.BRANCH and
a.DTETRM='99999999' and
a.AGNTNUM not between '00050000' and '00200000' and
a.agntnum <'00300000' and
a.agtype not in ('PA','LG','BK') and
c.EMPID='000101'
order by a.AGNTNUM";
return SqlHelper.ExecuteDataset(dwhConnString, CommandType.Text, strQuery);
}
and now use that column name to set Text and Value field.
public void loadSOCode()
{
DataSet ds = new DataSet();
ds = db.getSOCode();
if (ds.Tables[0].Rows.Count > 0)
{
ddlSoCode.DataSource = ds.Tables[0];
ddlSoCode.DataTextField ="NewColumn";
ddlSoCode.DataValueField = "NewColumn";
ddlSoCode.DataBind();
ddlSoCode.Items.Insert(0, new ListItem("--Select The Agent--", "--Select The Agent--"));
}
}

Compare query from database with string C#

I am making a program in C# with access database. I want to check if a string from the database is in a string.
I have a table named keyword and I have a string who has some text in it. So, I want to check if any of the strings in the database is in the text, one by one.
Let's say I have this in my database:
"ABC", "CDE", "EFG"
and I have this text:
string a = "and abc asd dsa efg"
And I want to fill a label - if is true "The string has ABC, EFG" else "NO MATCH"
Thanks in advance,
dnisko
First populate table column values into a string List.
SqlConnection cnn = new SqlConnection(/*Database connection credentails*/);
SqlDataAdapter da = new SqlDataAdapter("select columnName from table", con);
DataSet ds = new DataSet();
da.Fill(ds);
List<string> keyValues= new List<string>();
foreach(DataRow row in ds.Tables[0].Rows)
{
keyValues.Add(row["columnName"].ToString());
}
Then search for string in text one by one.
string a = "and abc asd dsa efg";
string matchedKeys=string.Empty;
bool matchFound = false;
foreach(string key in keyValues)
{
if(a.Contains(key))
{
matchFound=true;
matchedKeys + = key + ",";
}
}
if(matchFound)
lbl.Text = "The string has " + matchedKeys;
else
lblText = " NO Match Found !";
will be easier to achieve on Database side. For SQL Server it will be like
#lookup as your parameter
SELECT k.Word FROM Keywords k
WHERE #lookup like '%' + k.Work + '%'
This will return you a collection of keywords that were found in the string you passed as parameter to this query string (stored procedure)
try to use this
// list from DB
var list = new List<string> { "ABC", "CDE", "EFG" };
var selectedResult = new List<string>();
var a = "and abc asd dsa efg";
list.ForEach(x =>
{
var result = a.ToUpperInvariant().Contains(x.ToUpperInvariant());
if (result)
{
selectedResult.Add(x);
}
});
var joined = selectedResult.Count > 0 ? string.Join(",", selectedResult) : "No Match";

how to use row index as dataset index using c#.net

I am newbie to c# I am working on project i am trying to loop through data table containing distinct values
and my database has song id like:1,2,3,4,6,8,9,10
but dataset takes this values as 0,1,2,3,4,5,6,7 respectively... thanks
String sql = "select title, song_id from up_song where Song_type='Mp3 Tracks' ";
adpt = new SqlDataAdapter(sql, cn);
ds = new DataSet();
adpt.Fill(ds, "title");
var maxvalue = ds.Tables["title"].AsEnumerable().Max(x => x.Field<int>("song_id"));
var minvalue = ds.Tables["title"].AsEnumerable().Min(x => x.Field<int>("song_id"));
for (i =maxvalue; i >= minvalue; --i)
{
try
{
hyperlink[i] = new HyperLink();
hyperlink[i].ID = "hyperlink" + i;
hyperlink[i].Text = ds.Tables["title"].Rows[i].ItemArray[0].ToString();
hyperlink[i].NavigateUrl = "Downloadpage.aspx";
hyperlink[i].ForeColor = System.Drawing.Color.White;
Panel1.Controls.Add(hyperlink[i]);
Panel1.Controls.Add(new LiteralControl("<br>"));
HttpCookie coo = new HttpCookie("song");
coo["sogtit"] = ds.Tables["title"].Rows[i].ItemArray[0].ToString();
Response.Cookies.Add(coo);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
You are using the loop variable to acess the rows in the DataTable here:
coo["sogtit"] = ds.Tables["title"].Rows[i].ItemArray[0].ToString();
But the variable is initialized from the min and max ID values of your song_id.
I don't know why you need these values at all, why don't you loop the DataRows:
foreach(DataRow row in ds.Tables["title"].Rows)
{
// ...
int songID = row.Field<int>("song_id")
Hyperlink hl = new HyperLink(); // you don't need the array of hyperlinks neither
hl.ID = "hyperlink" + songID;
string title = row.Field<string>("title);
hl.Text = title;
coo["sogtit"] = title;
Panel1.Controls.Add(hl);
// ...
}
Update
i want to access those latest upload song so i use for loop and index
as min and max values. i mean want to access latest uploaded minimum 6
song
You could use Linq to get the last 6 uploaded songs:
var last6Uploaded = ds.Tables["title"].AsEnumerable()
.OrderByDescending(r => r.Field<int>("song_id"))
.Take(6);
foreach(DataRow row in last6Uploaded)
{
// ...
}
Note that you should use a DateTime field instead of the primary-key.
The array index (i) and the value of song_id should have nothing to do with each other. What if your song_id started at 1000? Or if your database indexed by song_id in descending order?

i want to check the the given value present in a dataset column or not

I want to check the given value present in a dataset column.
I was insert the value using separator and stored in a column name fld empname.
Example the dataset field fldempname have the value Hari,vinoth,Arun. suppose i ll insert again the value hari and arun means it display error message Like this Employee name already present otherwise the value inserted.
please help me..
My partial code is here..
for (int i = 0; i < lstbox.Items.Count; i++)
{
if (lstbox.Items[i].Selected)
{
string id = lstbox.Items[i].Text;
DataSet4TableAdapters.sp_getallattendancesetupTableAdapter TA1 = new DataSet4TableAdapters.sp_getallattendancesetupTableAdapter();
DataSet4.sp_getallattendancesetupDataTable DS1 = TA1.GetData();
if (DS1.Rows.Count == 0)
{
employee = employee + lstbox.Items[i].Text + ",";
}
else if (DS1.Rows.Count > 0)
{
foreach (DataRow dr in DS1.Rows)
{
foreach (string category in dr["fldemployee"].ToString().Split(','))
{
if (category != "")
{
if (category == id)
{
Value = Value + lstbox.Items[i].Text + "\\n";
break;
}
}
continue;
}
}
}
}
You can use the DataSet's Select() method:
DataRow[] foundRows;
foundRows = dataSet1.Tables["MyTable"].Select("fldempname = 'Hari'");
I haven't worked with datasets in a while.. so there prob is cleaner/better way to do this..
DataSet st = new DataSet();
foreach (DataRow row in st.Tables["table_name"].Rows)
{
if (row["column_name"] == "value")
{
//found
}
}
side note: i'd try Mitch Wheat's answer

Categories