データベースに 2 つの異なるテーブルがあり、それぞれが「SortOrder」に基づいてユーザーに表示されます。行 (またはエンティティ) を受け取り、その並べ替え順序をそれに最も近い順序 (実行されている関数に応じて上または下) に入れ替える 2 つの関数を作成しました。イベントが発生している場所 (同じ機能を持つ複数のグリッドビュー) に応じて、これらの関数を 2 つの異なるテーブルで機能させる必要があります。これが私がこれまでに持っているものです(繰り返しますが、 move downにはほぼ同じ機能がありますが、冗長になるため投稿しません):
protected void moveUp(String ValId, String dbName)
{
int ValueId = Convert.ToInt32(ValId);
DataModel.DataAccess.Entities dc = new DataModel.DataAccess.Entities();
if (dbName.ToLower() == "table1")
{
DataModel.DataAccess.Table1 currentValue = dc.Table1.Single(table1item => table1item.Table1ItemId == ValueId);
}
else if (dbName.ToLower() == "table2")
{
DataModel.DataAccess.Table2 currentValue = dc.Table2.Single(table2item => table2item.Table2ItemId == ValueId);
}
try
{
//make the change and update the database and gridview
}
catch (InvalidOperationException)
{
}
}
明らかな問題は、if ステートメントの前にcurrentValue変数を開始する必要があることです。そうしないと、変数が宣言されない可能性があり、したがって、関数の残りの部分 (currentValue 変数を使用する) が機能しません。
私の質問は次のとおりです。変数がまだどうなるかわからない場合、if ステートメントの前にどのように変数を初期化すればよいですか? 私はこれがうまくいくかもしれないと思っていましたが、まだ初期化する必要があると言われています (「暗黙的に型指定されたローカル変数を初期化する必要があります」):
var currentValue; //this is the line where I get the error message above
if (dbName.ToLower() == "table1")
{
currentValue = (DataModel.DataAccess.Table1)dc.Table1.Single(table1item => table1item.Table1ItemId == ValueId);
}
else if (dbName.ToLower() == "table2")
{
currentValue = (DataModel.DataAccess.Table2)dc.Table2.Single(table2item => table2item.Table2ItemId == ValueId);
}
[編集]私の質問をより正確に反映するようにタイトルを変更しました